Coverage Report

Created: 2023-02-04 01:27

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.89.3 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - Read FAQ at http://dearimgui.org/faq
6
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
7
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
8
// Read imgui.cpp for details, links and comments.
9
10
// Resources:
11
// - FAQ                   http://dearimgui.org/faq
12
// - Homepage & latest     https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/5243 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
19
// Getting Started?
20
// - For first-time users having issues compiling/linking/running or issues loading fonts:
21
//   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
23
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
24
// See LICENSE.txt for copyright and licensing details (standard MIT License).
25
// This library is free but needs your support to sustain development and maintenance.
26
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
27
// Individuals: you can support continued development via donations. See docs/README or web page.
28
29
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
30
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
31
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
32
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
33
// to a better solution or official support for them.
34
35
/*
36
37
Index of this file:
38
39
DOCUMENTATION
40
41
- MISSION STATEMENT
42
- END-USER GUIDE
43
- PROGRAMMER GUIDE
44
  - READ FIRST
45
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
46
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
47
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
48
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
49
  - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
50
- API BREAKING CHANGES (read me when you update!)
51
- FREQUENTLY ASKED QUESTIONS (FAQ)
52
  - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
53
54
CODE
55
(search for "[SECTION]" in the code to find them)
56
57
// [SECTION] INCLUDES
58
// [SECTION] FORWARD DECLARATIONS
59
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
60
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
61
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
62
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
63
// [SECTION] MISC HELPERS/UTILITIES (File functions)
64
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
65
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
66
// [SECTION] ImGuiStorage
67
// [SECTION] ImGuiTextFilter
68
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
69
// [SECTION] ImGuiListClipper
70
// [SECTION] STYLING
71
// [SECTION] RENDER HELPERS
72
// [SECTION] INITIALIZATION, SHUTDOWN
73
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
74
// [SECTION] INPUTS
75
// [SECTION] ERROR CHECKING
76
// [SECTION] LAYOUT
77
// [SECTION] SCROLLING
78
// [SECTION] TOOLTIPS
79
// [SECTION] POPUPS
80
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
81
// [SECTION] DRAG AND DROP
82
// [SECTION] LOGGING/CAPTURING
83
// [SECTION] SETTINGS
84
// [SECTION] LOCALIZATION
85
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
86
// [SECTION] DOCKING
87
// [SECTION] PLATFORM DEPENDENT HELPERS
88
// [SECTION] METRICS/DEBUGGER WINDOW
89
// [SECTION] DEBUG LOG WINDOW
90
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
91
92
*/
93
94
//-----------------------------------------------------------------------------
95
// DOCUMENTATION
96
//-----------------------------------------------------------------------------
97
98
/*
99
100
 MISSION STATEMENT
101
 =================
102
103
 - Easy to use to create code-driven and data-driven tools.
104
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
105
 - Easy to hack and improve.
106
 - Minimize setup and maintenance.
107
 - Minimize state storage on user side.
108
 - Minimize state synchronization.
109
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
110
 - Efficient runtime and memory consumption.
111
112
 Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
113
114
 - Doesn't look fancy, doesn't animate.
115
 - Limited layout features, intricate layouts are typically crafted in code.
116
117
118
 END-USER GUIDE
119
 ==============
120
121
 - Double-click on title bar to collapse window.
122
 - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
123
 - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
124
 - Click and drag on any empty space to move window.
125
 - TAB/SHIFT+TAB to cycle through keyboard editable fields.
126
 - CTRL+Click on a slider or drag box to input value as text.
127
 - Use mouse wheel to scroll.
128
 - Text editor:
129
   - Hold SHIFT or use mouse to select text.
130
   - CTRL+Left/Right to word jump.
131
   - CTRL+Shift+Left/Right to select words.
132
   - CTRL+A or Double-Click to select all.
133
   - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
134
   - CTRL+Z,CTRL+Y to undo/redo.
135
   - ESCAPE to revert text to its original value.
136
   - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
137
 - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
138
 - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. Download controller mapping PNG/PSD at http://dearimgui.org/controls_sheets
139
140
141
 PROGRAMMER GUIDE
142
 ================
143
144
 READ FIRST
145
 ----------
146
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
147
 - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
148
   destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
149
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
150
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
151
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
152
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
153
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
154
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
155
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
156
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
157
 - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
158
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
159
   If you get an assert, read the messages and comments around the assert.
160
 - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
161
 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
162
   See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
163
   However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
164
 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
165
166
167
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
168
 ----------------------------------------------
169
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
170
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
171
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
172
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
173
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
174
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
175
   likely be a comment about it. Please report any issue to the GitHub page!
176
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
177
 - Try to keep your copy of Dear ImGui reasonably up to date.
178
179
180
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
181
 ---------------------------------------------------------------
182
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
183
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
184
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
185
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
186
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
187
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
188
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
189
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
190
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
191
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
192
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
193
194
195
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
196
 --------------------------------------
197
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
198
 The sub-folders in examples/ contain examples applications following this structure.
199
200
     // Application init: create a dear imgui context, setup some options, load fonts
201
     ImGui::CreateContext();
202
     ImGuiIO& io = ImGui::GetIO();
203
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
204
     // TODO: Fill optional fields of the io structure later.
205
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
206
207
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
208
     ImGui_ImplWin32_Init(hwnd);
209
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
210
211
     // Application main loop
212
     while (true)
213
     {
214
         // Feed inputs to dear imgui, start new frame
215
         ImGui_ImplDX11_NewFrame();
216
         ImGui_ImplWin32_NewFrame();
217
         ImGui::NewFrame();
218
219
         // Any application code here
220
         ImGui::Text("Hello, world!");
221
222
         // Render dear imgui into screen
223
         ImGui::Render();
224
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
225
         g_pSwapChain->Present(1, 0);
226
     }
227
228
     // Shutdown
229
     ImGui_ImplDX11_Shutdown();
230
     ImGui_ImplWin32_Shutdown();
231
     ImGui::DestroyContext();
232
233
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
234
235
     // Application init: create a dear imgui context, setup some options, load fonts
236
     ImGui::CreateContext();
237
     ImGuiIO& io = ImGui::GetIO();
238
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
239
     // TODO: Fill optional fields of the io structure later.
240
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
241
242
     // Build and load the texture atlas into a texture
243
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
244
     int width, height;
245
     unsigned char* pixels = NULL;
246
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
247
248
     // At this point you've got the texture data and you need to upload that to your graphic system:
249
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
250
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
251
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
252
     io.Fonts->SetTexID((void*)texture);
253
254
     // Application main loop
255
     while (true)
256
     {
257
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
258
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
259
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
260
        io.DisplaySize.x = 1920.0f;             // set the current display width
261
        io.DisplaySize.y = 1280.0f;             // set the current display height here
262
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
263
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
264
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
265
266
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
267
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
268
        ImGui::NewFrame();
269
270
        // Most of your application code here
271
        ImGui::Text("Hello, world!");
272
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
273
        MyGameRender(); // may use any Dear ImGui functions as well!
274
275
        // Render dear imgui, swap buffers
276
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
277
        ImGui::EndFrame();
278
        ImGui::Render();
279
        ImDrawData* draw_data = ImGui::GetDrawData();
280
        MyImGuiRenderFunction(draw_data);
281
        SwapBuffers();
282
     }
283
284
     // Shutdown
285
     ImGui::DestroyContext();
286
287
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
288
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
289
 Please read the FAQ and example applications for details about this!
290
291
292
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
293
 ---------------------------------------------
294
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
295
296
    void MyImGuiRenderFunction(ImDrawData* draw_data)
297
    {
298
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
299
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
300
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
301
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
302
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
303
       ImVec2 clip_off = draw_data->DisplayPos;
304
       for (int n = 0; n < draw_data->CmdListsCount; n++)
305
       {
306
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
307
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
308
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
309
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
310
          {
311
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
312
             if (pcmd->UserCallback)
313
             {
314
                 pcmd->UserCallback(cmd_list, pcmd);
315
             }
316
             else
317
             {
318
                 // Project scissor/clipping rectangles into framebuffer space
319
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
320
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
321
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
322
                     continue;
323
324
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
325
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
326
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
327
                 // - Clipping coordinates are provided in imgui coordinates space:
328
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
329
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
330
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
331
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
332
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
333
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
334
335
                 // The texture for the draw call is specified by pcmd->GetTexID().
336
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
337
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
338
339
                 // Render 'pcmd->ElemCount/3' indexed triangles.
340
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
341
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
342
             }
343
          }
344
       }
345
    }
346
347
348
 USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
349
 ------------------------------------------
350
 - The gamepad/keyboard navigation is fairly functional and keeps being improved.
351
 - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
352
 - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
353
 - Keyboard:
354
    - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
355
    - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard),
356
      the io.WantCaptureKeyboard flag will be set. For more advanced uses, you may want to read from:
357
       - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
358
       - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
359
       - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
360
      Please reach out if you think the game vs navigation input sharing could be improved.
361
 - Gamepad:
362
    - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
363
    - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
364
      For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
365
      Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
366
    - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
367
    - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://dearimgui.org/controls_sheets
368
    - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
369
      with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
370
 - Mouse:
371
    - PS4/PS5 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
372
    - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
373
    - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
374
      Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
375
      When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
376
      When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
377
      (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse moving back and forth!)
378
      (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
379
       to set a boolean to ignore your other external mouse positions until the external source is moved again.)
380
381
382
 API BREAKING CHANGES
383
 ====================
384
385
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
386
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
387
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
388
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
389
390
(Docking/Viewport Branch)
391
 - 2022/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
392
                        - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
393
                          you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
394
                        - likewise io.MousePos and GetMousePos() will use OS coordinates.
395
                          If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
396
397
 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
398
 - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
399
 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
400
                         - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
401
                         - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
402
                         - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
403
                         - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
404
                       the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
405
                       the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
406
                       exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
407
 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
408
                       this will require uses of legacy backend-dependent indices to be casted, e.g.
409
                          - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
410
                          - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
411
                          - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
412
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
413
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
414
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
415
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
416
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
417
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
418
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
419
                         - previously this would make the window content size ~200x200:
420
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
421
                         - instead, please submit an item:
422
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
423
                         - alternative:
424
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
425
                         - content size is now only extended when submitting an item!
426
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
427
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
428
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
429
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
430
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
431
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
432
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
433
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
434
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
435
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
436
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
437
                        - Official backends from 1.87+                  -> no issue.
438
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
439
                        - Custom backends not writing to io.NavInputs[] -> no issue.
440
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
441
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
442
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
443
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
444
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
445
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
446
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
447
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
448
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
449
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
450
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
451
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
452
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
453
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
454
                       read https://github.com/ocornut/imgui/issues/4921 for details.
455
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
456
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
457
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
458
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
459
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
460
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
461
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
462
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
463
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
464
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
465
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
466
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
467
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
468
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
469
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
470
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
471
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
472
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
473
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
474
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
475
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
476
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
477
                        - if you are using official backends from the source tree: you have nothing to do.
478
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
479
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
480
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
481
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
482
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
483
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
484
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
485
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
486
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
487
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
488
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
489
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
490
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
491
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
492
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
493
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
494
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
495
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
496
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
497
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
498
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
499
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
500
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
501
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
502
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
503
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
504
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
505
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
506
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
507
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
508
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
509
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
510
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
511
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
512
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
513
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
514
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
515
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
516
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
517
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
518
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
519
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
520
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
521
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
522
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
523
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
524
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
525
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
526
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
527
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
528
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
529
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
530
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
531
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
532
                       - if you omitted the 'power' parameter (likely!), you are not affected.
533
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
534
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
535
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
536
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
537
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
538
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
539
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
540
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
541
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
542
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
543
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
544
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
545
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
546
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
547
                       - ShowTestWindow()                    -> use ShowDemoWindow()
548
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
549
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
550
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
551
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
552
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
553
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
554
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
555
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
556
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
557
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
558
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
559
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
560
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
561
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
562
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
563
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
564
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
565
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
566
                       - ImFont::Glyph                       -> use ImFontGlyph
567
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
568
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
569
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
570
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
571
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
572
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
573
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
574
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
575
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
576
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
577
                       Please reach out if you are affected.
578
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
579
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
580
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
581
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
582
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
583
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
584
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
585
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
586
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
587
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
588
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
589
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
590
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
591
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
592
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
593
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
594
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
595
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
596
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
597
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
598
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
599
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
600
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
601
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
602
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
603
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
604
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
605
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
606
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
607
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
608
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
609
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
610
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
611
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
612
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
613
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
614
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
615
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
616
                       consistent with other functions. Kept redirection functions (will obsolete).
617
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
618
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
619
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
620
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
621
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
622
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
623
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
624
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
625
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
626
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
627
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
628
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
629
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
630
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
631
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
632
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
633
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
634
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
635
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
636
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
637
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
638
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
639
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
640
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
641
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
642
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
643
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
644
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
645
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
646
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
647
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
648
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
649
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
650
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
651
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
652
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
653
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
654
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
655
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
656
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
657
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
658
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
659
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
660
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
661
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
662
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
663
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
664
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
665
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
666
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
667
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
668
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
669
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
670
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
671
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
672
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
673
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
674
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
675
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
676
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
677
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
678
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
679
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
680
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
681
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
682
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
683
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
684
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
685
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
686
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
687
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
688
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
689
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
690
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
691
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
692
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
693
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
694
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
695
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
696
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
697
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
698
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
699
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
700
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
701
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
702
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
703
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
704
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
705
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
706
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
707
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
708
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
709
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
710
                     - the signature of the io.RenderDrawListsFn handler has changed!
711
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
712
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
713
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
714
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
715
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
716
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
717
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
718
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
719
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
720
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
721
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
722
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
723
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
724
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
725
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
726
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
727
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
728
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
729
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
730
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
731
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
732
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
733
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
734
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
735
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
736
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
737
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
738
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
739
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
740
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
741
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
742
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
743
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
744
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
745
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
746
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
747
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
748
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
749
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
750
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
751
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
752
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
753
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
754
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
755
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
756
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
757
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
758
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
759
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
760
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
761
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
762
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
763
764
765
 FREQUENTLY ASKED QUESTIONS (FAQ)
766
 ================================
767
768
 Read all answers online:
769
   https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
770
 Read all answers locally (with a text editor or ideally a Markdown viewer):
771
   docs/FAQ.md
772
 Some answers are copied down here to facilitate searching in code.
773
774
 Q&A: Basics
775
 ===========
776
777
 Q: Where is the documentation?
778
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
779
    - Run the examples/ and explore them.
780
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
781
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
782
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
783
    - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
784
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
785
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
786
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
787
    - Your programming IDE is your friend, find the type or function declaration to find comments
788
      associated with it.
789
790
 Q: What is this library called?
791
 Q: Which version should I get?
792
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
793
 >> See https://www.dearimgui.org/faq for details.
794
795
 Q&A: Integration
796
 ================
797
798
 Q: How to get started?
799
 A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
800
801
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
802
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
803
 >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.
804
805
 Q. How can I enable keyboard controls?
806
 Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
807
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
808
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
809
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
810
 >> See https://www.dearimgui.org/faq
811
812
 Q&A: Usage
813
 ----------
814
815
 Q: About the ID Stack system..
816
   - Why is my widget not reacting when I click on it?
817
   - How can I have widgets with an empty label?
818
   - How can I have multiple widgets with the same label?
819
   - How can I have multiple windows with the same label?
820
 Q: How can I display an image? What is ImTextureID, how does it work?
821
 Q: How can I use my own math types instead of ImVec2/ImVec4?
822
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
823
 Q: How can I display custom shapes? (using low-level ImDrawList API)
824
 >> See https://www.dearimgui.org/faq
825
826
 Q&A: Fonts, Text
827
 ================
828
829
 Q: How should I handle DPI in my application?
830
 Q: How can I load a different font than the default?
831
 Q: How can I easily use icons in my application?
832
 Q: How can I load multiple fonts?
833
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
834
 >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
835
836
 Q&A: Concerns
837
 =============
838
839
 Q: Who uses Dear ImGui?
840
 Q: Can you create elaborate/serious tools with Dear ImGui?
841
 Q: Can you reskin the look of Dear ImGui?
842
 Q: Why using C++ (as opposed to C)?
843
 >> See https://www.dearimgui.org/faq
844
845
 Q&A: Community
846
 ==============
847
848
 Q: How can I help?
849
 A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
850
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
851
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
852
    - Individuals: you can support continued development via PayPal donations. See README.
853
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
854
      and see how you want to help and can help!
855
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
856
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
857
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
858
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
859
860
*/
861
862
//-------------------------------------------------------------------------
863
// [SECTION] INCLUDES
864
//-------------------------------------------------------------------------
865
866
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
867
#define _CRT_SECURE_NO_WARNINGS
868
#endif
869
870
#include "imgui.h"
871
#ifndef IMGUI_DISABLE
872
873
#ifndef IMGUI_DEFINE_MATH_OPERATORS
874
#define IMGUI_DEFINE_MATH_OPERATORS
875
#endif
876
#include "imgui_internal.h"
877
878
// System includes
879
#include <stdio.h>      // vsnprintf, sscanf, printf
880
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
881
#include <stddef.h>     // intptr_t
882
#else
883
#include <stdint.h>     // intptr_t
884
#endif
885
886
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
887
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
888
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
889
#endif
890
891
// [Windows] OS specific includes (optional)
892
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
893
#define IMGUI_DISABLE_WIN32_FUNCTIONS
894
#endif
895
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
896
#ifndef WIN32_LEAN_AND_MEAN
897
#define WIN32_LEAN_AND_MEAN
898
#endif
899
#ifndef NOMINMAX
900
#define NOMINMAX
901
#endif
902
#ifndef __MINGW32__
903
#include <Windows.h>        // _wfopen, OpenClipboard
904
#else
905
#include <windows.h>
906
#endif
907
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
908
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
909
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
910
#endif
911
#endif
912
913
// [Apple] OS specific includes
914
#if defined(__APPLE__)
915
#include <TargetConditionals.h>
916
#endif
917
918
// Visual Studio warnings
919
#ifdef _MSC_VER
920
#pragma warning (disable: 4127)             // condition expression is constant
921
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
922
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
923
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
924
#endif
925
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
926
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
927
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
928
#endif
929
930
// Clang/GCC warnings with -Weverything
931
#if defined(__clang__)
932
#if __has_warning("-Wunknown-warning-option")
933
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
934
#endif
935
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
936
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
937
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
938
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
939
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
940
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
941
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
942
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
943
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
944
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
945
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
946
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
947
#elif defined(__GNUC__)
948
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
949
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
950
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
951
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
952
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
953
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
954
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
955
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
956
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
957
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
958
#endif
959
960
// Debug options
961
180k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
962
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
963
#define IMGUI_DEBUG_INI_SETTINGS    0   // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
964
965
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
966
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
967
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
968
969
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
970
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
971
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
972
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
973
974
// Docking
975
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
976
static const float DOCKING_SPLITTER_SIZE                    = 2.0f;
977
978
//-------------------------------------------------------------------------
979
// [SECTION] FORWARD DECLARATIONS
980
//-------------------------------------------------------------------------
981
982
static void             SetCurrentWindow(ImGuiWindow* window);
983
static void             FindHoveredWindow();
984
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
985
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
986
987
static void             AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
988
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
989
990
// Settings
991
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
992
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
993
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
994
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
995
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
996
997
// Platform Dependents default implementation for IO functions
998
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data);
999
static void             SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
1000
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1001
1002
namespace ImGui
1003
{
1004
// Navigation
1005
static void             NavUpdate();
1006
static void             NavUpdateWindowing();
1007
static void             NavUpdateWindowingOverlay();
1008
static void             NavUpdateCancelRequest();
1009
static void             NavUpdateCreateMoveRequest();
1010
static void             NavUpdateCreateTabbingRequest();
1011
static float            NavUpdatePageUpPageDown();
1012
static inline void      NavUpdateAnyRequestFlag();
1013
static void             NavUpdateCreateWrappingRequest();
1014
static void             NavEndFrame();
1015
static bool             NavScoreItem(ImGuiNavItemData* result);
1016
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1017
static void             NavProcessItem();
1018
static void             NavProcessItemForTabbingRequest(ImGuiID id);
1019
static ImVec2           NavCalcPreferredRefPos();
1020
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1021
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1022
static void             NavRestoreLayer(ImGuiNavLayer layer);
1023
static void             NavRestoreHighlightAfterMove();
1024
static int              FindWindowFocusIndex(ImGuiWindow* window);
1025
1026
// Error Checking and Debug Tools
1027
static void             ErrorCheckNewFrameSanityChecks();
1028
static void             ErrorCheckEndFrameSanityChecks();
1029
static void             UpdateDebugToolItemPicker();
1030
static void             UpdateDebugToolStackQueries();
1031
1032
// Inputs
1033
static void             UpdateKeyboardInputs();
1034
static void             UpdateMouseInputs();
1035
static void             UpdateMouseWheel();
1036
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1037
1038
// Misc
1039
static void             UpdateSettings();
1040
static bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1041
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1042
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1043
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1044
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1045
static void             RenderDimmedBackgrounds();
1046
static ImGuiWindow*     FindBlockingModal(ImGuiWindow* window);
1047
1048
// Viewports
1049
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1050
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1051
static void             DestroyViewport(ImGuiViewportP* viewport);
1052
static void             UpdateViewportsNewFrame();
1053
static void             UpdateViewportsEndFrame();
1054
static void             WindowSelectViewport(ImGuiWindow* window);
1055
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1056
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1057
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1058
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1059
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1060
static int              FindPlatformMonitorForRect(const ImRect& r);
1061
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1062
1063
}
1064
1065
//-----------------------------------------------------------------------------
1066
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1067
//-----------------------------------------------------------------------------
1068
1069
// DLL users:
1070
// - Heaps and globals are not shared across DLL boundaries!
1071
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1072
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1073
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1074
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1075
1076
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1077
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1078
//   Change to a different context by calling ImGui::SetCurrentContext().
1079
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1080
//   If you want thread-safety to allow N threads to access N different contexts:
1081
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1082
//         struct ImGuiContext;
1083
//         extern thread_local ImGuiContext* MyImGuiTLS;
1084
//         #define GImGui MyImGuiTLS
1085
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1086
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1087
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1088
// - DLL users: read comments above.
1089
#ifndef GImGui
1090
ImGuiContext*   GImGui = NULL;
1091
#endif
1092
1093
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1094
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1095
// - DLL users: read comments above.
1096
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1097
1.20k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1098
1.16k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1099
#else
1100
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1101
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1102
#endif
1103
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1104
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1105
static void*                GImAllocatorUserData = NULL;
1106
1107
//-----------------------------------------------------------------------------
1108
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1109
//-----------------------------------------------------------------------------
1110
1111
ImGuiStyle::ImGuiStyle()
1112
1
{
1113
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1114
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1115
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1116
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1117
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1118
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1119
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1120
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1121
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1122
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1123
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1124
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1125
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1126
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1127
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1128
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1129
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1130
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell
1131
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1132
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1133
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1134
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1135
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1136
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1137
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1138
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1139
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1140
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1141
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1142
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1143
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1144
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1145
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1146
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1147
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1148
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1149
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1150
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1151
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1152
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1153
1154
    // Default theme
1155
1
    ImGui::StyleColorsDark(this);
1156
1
}
1157
1158
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1159
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1160
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1161
0
{
1162
0
    WindowPadding = ImFloor(WindowPadding * scale_factor);
1163
0
    WindowRounding = ImFloor(WindowRounding * scale_factor);
1164
0
    WindowMinSize = ImFloor(WindowMinSize * scale_factor);
1165
0
    ChildRounding = ImFloor(ChildRounding * scale_factor);
1166
0
    PopupRounding = ImFloor(PopupRounding * scale_factor);
1167
0
    FramePadding = ImFloor(FramePadding * scale_factor);
1168
0
    FrameRounding = ImFloor(FrameRounding * scale_factor);
1169
0
    ItemSpacing = ImFloor(ItemSpacing * scale_factor);
1170
0
    ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
1171
0
    CellPadding = ImFloor(CellPadding * scale_factor);
1172
0
    TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
1173
0
    IndentSpacing = ImFloor(IndentSpacing * scale_factor);
1174
0
    ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
1175
0
    ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
1176
0
    ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
1177
0
    GrabMinSize = ImFloor(GrabMinSize * scale_factor);
1178
0
    GrabRounding = ImFloor(GrabRounding * scale_factor);
1179
0
    LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
1180
0
    TabRounding = ImFloor(TabRounding * scale_factor);
1181
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1182
0
    DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
1183
0
    DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
1184
0
    MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
1185
0
}
1186
1187
ImGuiIO::ImGuiIO()
1188
1
{
1189
    // Most fields are initialized with zero
1190
1
    memset(this, 0, sizeof(*this));
1191
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1192
1193
    // Settings
1194
1
    ConfigFlags = ImGuiConfigFlags_None;
1195
1
    BackendFlags = ImGuiBackendFlags_None;
1196
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1197
1
    DeltaTime = 1.0f / 60.0f;
1198
1
    IniSavingRate = 5.0f;
1199
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1200
1
    LogFilename = "imgui_log.txt";
1201
1
    MouseDoubleClickTime = 0.30f;
1202
1
    MouseDoubleClickMaxDist = 6.0f;
1203
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1204
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1205
        KeyMap[i] = -1;
1206
#endif
1207
1
    KeyRepeatDelay = 0.275f;
1208
1
    KeyRepeatRate = 0.050f;
1209
1
    HoverDelayNormal = 0.30f;
1210
1
    HoverDelayShort = 0.10f;
1211
1
    UserData = NULL;
1212
1213
1
    Fonts = NULL;
1214
1
    FontGlobalScale = 1.0f;
1215
1
    FontDefault = NULL;
1216
1
    FontAllowUserScaling = false;
1217
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1218
1219
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1220
1
    ConfigDockingNoSplit = false;
1221
1
    ConfigDockingWithShift = false;
1222
1
    ConfigDockingAlwaysTabBar = false;
1223
1
    ConfigDockingTransparentPayload = false;
1224
1225
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1226
1
    ConfigViewportsNoAutoMerge = false;
1227
1
    ConfigViewportsNoTaskBarIcon = false;
1228
1
    ConfigViewportsNoDecoration = true;
1229
1
    ConfigViewportsNoDefaultParent = false;
1230
1231
    // Miscellaneous options
1232
1
    MouseDrawCursor = false;
1233
#ifdef __APPLE__
1234
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1235
#else
1236
1
    ConfigMacOSXBehaviors = false;
1237
1
#endif
1238
1
    ConfigInputTrickleEventQueue = true;
1239
1
    ConfigInputTextCursorBlink = true;
1240
1
    ConfigInputTextEnterKeepActive = false;
1241
1
    ConfigDragClickToInputText = false;
1242
1
    ConfigWindowsResizeFromEdges = true;
1243
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1244
1
    ConfigMemoryCompactTimer = 60.0f;
1245
1246
    // Platform Functions
1247
1
    BackendPlatformName = BackendRendererName = NULL;
1248
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1249
1
    GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;   // Platform dependent default implementations
1250
1
    SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
1251
1
    ClipboardUserData = NULL;
1252
1
    SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
1253
1254
    // Input (NB: we already have memset zero the entire structure!)
1255
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1256
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1257
1
    MouseDragThreshold = 6.0f;
1258
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1259
141
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1260
1
    AppAcceptingEvents = true;
1261
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1262
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1263
1
}
1264
1265
// Pass in translated ASCII characters for text input.
1266
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1267
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1268
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1269
void ImGuiIO::AddInputCharacter(unsigned int c)
1270
15.0k
{
1271
15.0k
    ImGuiContext& g = *GImGui;
1272
15.0k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1273
15.0k
    if (c == 0 || !AppAcceptingEvents)
1274
6.42k
        return;
1275
1276
8.61k
    ImGuiInputEvent e;
1277
8.61k
    e.Type = ImGuiInputEventType_Text;
1278
8.61k
    e.Source = ImGuiInputSource_Keyboard;
1279
8.61k
    e.Text.Char = c;
1280
8.61k
    g.InputEventsQueue.push_back(e);
1281
8.61k
}
1282
1283
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1284
// we should save the high surrogate.
1285
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1286
1.68k
{
1287
1.68k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1288
76
        return;
1289
1290
1.61k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1291
820
    {
1292
820
        if (InputQueueSurrogate != 0)
1293
233
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1294
820
        InputQueueSurrogate = c;
1295
820
        return;
1296
820
    }
1297
1298
793
    ImWchar cp = c;
1299
793
    if (InputQueueSurrogate != 0)
1300
579
    {
1301
579
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1302
579
        {
1303
579
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1304
579
        }
1305
0
        else
1306
0
        {
1307
0
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1308
0
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1309
#else
1310
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1311
#endif
1312
0
        }
1313
1314
579
        InputQueueSurrogate = 0;
1315
579
    }
1316
793
    AddInputCharacter((unsigned)cp);
1317
793
}
1318
1319
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1320
70
{
1321
70
    if (!AppAcceptingEvents)
1322
0
        return;
1323
70
    while (*utf8_chars != 0)
1324
0
    {
1325
0
        unsigned int c = 0;
1326
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1327
0
        AddInputCharacter(c);
1328
0
    }
1329
70
}
1330
1331
// FIXME: Perhaps we could clear queued events as well?
1332
void ImGuiIO::ClearInputCharacters()
1333
9.34k
{
1334
9.34k
    InputQueueCharacters.resize(0);
1335
9.34k
}
1336
1337
// FIXME: Perhaps we could clear queued events as well?
1338
void ImGuiIO::ClearInputKeys()
1339
13.7k
{
1340
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1341
    memset(KeysDown, 0, sizeof(KeysDown));
1342
#endif
1343
1.93M
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1344
1.92M
    {
1345
1.92M
        KeysData[n].Down             = false;
1346
1.92M
        KeysData[n].DownDuration     = -1.0f;
1347
1.92M
        KeysData[n].DownDurationPrev = -1.0f;
1348
1.92M
    }
1349
13.7k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1350
13.7k
    KeyMods = ImGuiMod_None;
1351
13.7k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1352
82.4k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1353
68.6k
    {
1354
68.6k
        MouseDown[n] = false;
1355
68.6k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1356
68.6k
    }
1357
13.7k
    MouseWheel = MouseWheelH = 0.0f;
1358
13.7k
}
1359
1360
static ImGuiInputEvent* FindLatestInputEvent(ImGuiInputEventType type, int arg = -1)
1361
44.0k
{
1362
44.0k
    ImGuiContext& g = *GImGui;
1363
74.5k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1364
40.6k
    {
1365
40.6k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1366
40.6k
        if (e->Type != type)
1367
25.6k
            continue;
1368
15.0k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1369
287
            continue;
1370
14.7k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1371
4.57k
            continue;
1372
10.1k
        return e;
1373
14.7k
    }
1374
33.8k
    return NULL;
1375
44.0k
}
1376
1377
// Queue a new key down/up event.
1378
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1379
// - bool down:          Is the key down? use false to signify a key release.
1380
// - float analog_value: 0.0f..1.0f
1381
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1382
3.73k
{
1383
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1384
3.73k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1385
0
        return;
1386
3.73k
    ImGuiContext& g = *GImGui;
1387
3.73k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1388
3.73k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1389
3.73k
    IM_ASSERT(!ImGui::IsAliasKey(key)); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1390
3.73k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1391
1392
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1393
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1394
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1395
    if (BackendUsingLegacyKeyArrays == -1)
1396
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1397
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1398
    BackendUsingLegacyKeyArrays = 0;
1399
#endif
1400
3.73k
    if (ImGui::IsGamepadKey(key))
1401
0
        BackendUsingLegacyNavInputArray = false;
1402
1403
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1404
3.73k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_Key, (int)key);
1405
3.73k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(key);
1406
3.73k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1407
3.73k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1408
3.73k
    if (latest_key_down == down && latest_key_analog == analog_value)
1409
462
        return;
1410
1411
    // Add event
1412
3.27k
    ImGuiInputEvent e;
1413
3.27k
    e.Type = ImGuiInputEventType_Key;
1414
3.27k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1415
3.27k
    e.Key.Key = key;
1416
3.27k
    e.Key.Down = down;
1417
3.27k
    e.Key.AnalogValue = analog_value;
1418
3.27k
    g.InputEventsQueue.push_back(e);
1419
3.27k
}
1420
1421
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1422
970
{
1423
970
    if (!AppAcceptingEvents)
1424
0
        return;
1425
970
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1426
970
}
1427
1428
// [Optional] Call after AddKeyEvent().
1429
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1430
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1431
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1432
0
{
1433
0
    if (key == ImGuiKey_None)
1434
0
        return;
1435
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1436
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1437
0
    IM_UNUSED(native_keycode);  // Yet unused
1438
0
    IM_UNUSED(native_scancode); // Yet unused
1439
1440
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1441
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1442
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1443
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1444
        return;
1445
    KeyMap[legacy_key] = key;
1446
    KeyMap[key] = legacy_key;
1447
#else
1448
0
    IM_UNUSED(key);
1449
0
    IM_UNUSED(native_legacy_index);
1450
0
#endif
1451
0
}
1452
1453
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1454
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1455
0
{
1456
0
    AppAcceptingEvents = accepting_events;
1457
0
}
1458
1459
// Queue a mouse move event
1460
void ImGuiIO::AddMousePosEvent(float x, float y)
1461
9.30k
{
1462
9.30k
    ImGuiContext& g = *GImGui;
1463
9.30k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1464
9.30k
    if (!AppAcceptingEvents)
1465
0
        return;
1466
1467
    // Apply same flooring as UpdateMouseInputs()
1468
9.30k
    ImVec2 pos((x > -FLT_MAX) ? ImFloorSigned(x) : x, (y > -FLT_MAX) ? ImFloorSigned(y) : y);
1469
1470
    // Filter duplicate
1471
9.30k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MousePos);
1472
9.30k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1473
9.30k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1474
3.79k
        return;
1475
1476
5.50k
    ImGuiInputEvent e;
1477
5.50k
    e.Type = ImGuiInputEventType_MousePos;
1478
5.50k
    e.Source = ImGuiInputSource_Mouse;
1479
5.50k
    e.MousePos.PosX = pos.x;
1480
5.50k
    e.MousePos.PosY = pos.y;
1481
5.50k
    g.InputEventsQueue.push_back(e);
1482
5.50k
}
1483
1484
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1485
23.5k
{
1486
23.5k
    ImGuiContext& g = *GImGui;
1487
23.5k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1488
23.5k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1489
23.5k
    if (!AppAcceptingEvents)
1490
0
        return;
1491
1492
    // Filter duplicate
1493
23.5k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MouseButton, (int)mouse_button);
1494
23.5k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1495
23.5k
    if (latest_button_down == down)
1496
12.7k
        return;
1497
1498
10.7k
    ImGuiInputEvent e;
1499
10.7k
    e.Type = ImGuiInputEventType_MouseButton;
1500
10.7k
    e.Source = ImGuiInputSource_Mouse;
1501
10.7k
    e.MouseButton.Button = mouse_button;
1502
10.7k
    e.MouseButton.Down = down;
1503
10.7k
    g.InputEventsQueue.push_back(e);
1504
10.7k
}
1505
1506
// Queue a mouse wheel event (most mouse/API will only have a Y component)
1507
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1508
4.18k
{
1509
4.18k
    ImGuiContext& g = *GImGui;
1510
4.18k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1511
1512
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1513
4.18k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1514
132
        return;
1515
1516
4.05k
    ImGuiInputEvent e;
1517
4.05k
    e.Type = ImGuiInputEventType_MouseWheel;
1518
4.05k
    e.Source = ImGuiInputSource_Mouse;
1519
4.05k
    e.MouseWheel.WheelX = wheel_x;
1520
4.05k
    e.MouseWheel.WheelY = wheel_y;
1521
4.05k
    g.InputEventsQueue.push_back(e);
1522
4.05k
}
1523
1524
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1525
0
{
1526
0
    ImGuiContext& g = *GImGui;
1527
0
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1528
0
    IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1529
0
    if (!AppAcceptingEvents)
1530
0
        return;
1531
1532
    // Filter duplicate
1533
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MouseViewport);
1534
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1535
0
    if (latest_viewport_id == viewport_id)
1536
0
        return;
1537
1538
0
    ImGuiInputEvent e;
1539
0
    e.Type = ImGuiInputEventType_MouseViewport;
1540
0
    e.Source = ImGuiInputSource_Mouse;
1541
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1542
0
    g.InputEventsQueue.push_back(e);
1543
0
}
1544
1545
void ImGuiIO::AddFocusEvent(bool focused)
1546
7.41k
{
1547
7.41k
    ImGuiContext& g = *GImGui;
1548
7.41k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1549
1550
    // Filter duplicate
1551
7.41k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_Focus);
1552
7.41k
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1553
7.41k
    if (latest_focused == focused)
1554
1.08k
        return;
1555
1556
6.33k
    ImGuiInputEvent e;
1557
6.33k
    e.Type = ImGuiInputEventType_Focus;
1558
6.33k
    e.AppFocused.Focused = focused;
1559
6.33k
    g.InputEventsQueue.push_back(e);
1560
6.33k
}
1561
1562
//-----------------------------------------------------------------------------
1563
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1564
//-----------------------------------------------------------------------------
1565
1566
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1567
0
{
1568
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1569
0
    ImVec2 p_last = p1;
1570
0
    ImVec2 p_closest;
1571
0
    float p_closest_dist2 = FLT_MAX;
1572
0
    float t_step = 1.0f / (float)num_segments;
1573
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1574
0
    {
1575
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1576
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1577
0
        float dist2 = ImLengthSqr(p - p_line);
1578
0
        if (dist2 < p_closest_dist2)
1579
0
        {
1580
0
            p_closest = p_line;
1581
0
            p_closest_dist2 = dist2;
1582
0
        }
1583
0
        p_last = p_current;
1584
0
    }
1585
0
    return p_closest;
1586
0
}
1587
1588
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1589
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1590
0
{
1591
0
    float dx = x4 - x1;
1592
0
    float dy = y4 - y1;
1593
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1594
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1595
0
    d2 = (d2 >= 0) ? d2 : -d2;
1596
0
    d3 = (d3 >= 0) ? d3 : -d3;
1597
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1598
0
    {
1599
0
        ImVec2 p_current(x4, y4);
1600
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1601
0
        float dist2 = ImLengthSqr(p - p_line);
1602
0
        if (dist2 < p_closest_dist2)
1603
0
        {
1604
0
            p_closest = p_line;
1605
0
            p_closest_dist2 = dist2;
1606
0
        }
1607
0
        p_last = p_current;
1608
0
    }
1609
0
    else if (level < 10)
1610
0
    {
1611
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1612
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1613
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1614
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1615
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1616
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1617
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1618
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1619
0
    }
1620
0
}
1621
1622
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1623
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1624
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1625
0
{
1626
0
    IM_ASSERT(tess_tol > 0.0f);
1627
0
    ImVec2 p_last = p1;
1628
0
    ImVec2 p_closest;
1629
0
    float p_closest_dist2 = FLT_MAX;
1630
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1631
0
    return p_closest;
1632
0
}
1633
1634
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1635
0
{
1636
0
    ImVec2 ap = p - a;
1637
0
    ImVec2 ab_dir = b - a;
1638
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1639
0
    if (dot < 0.0f)
1640
0
        return a;
1641
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1642
0
    if (dot > ab_len_sqr)
1643
0
        return b;
1644
0
    return a + ab_dir * dot / ab_len_sqr;
1645
0
}
1646
1647
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1648
0
{
1649
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1650
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1651
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1652
0
    return ((b1 == b2) && (b2 == b3));
1653
0
}
1654
1655
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1656
0
{
1657
0
    ImVec2 v0 = b - a;
1658
0
    ImVec2 v1 = c - a;
1659
0
    ImVec2 v2 = p - a;
1660
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1661
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1662
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1663
0
    out_u = 1.0f - out_v - out_w;
1664
0
}
1665
1666
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1667
0
{
1668
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1669
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1670
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1671
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1672
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1673
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1674
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1675
0
    if (m == dist2_ab)
1676
0
        return proj_ab;
1677
0
    if (m == dist2_bc)
1678
0
        return proj_bc;
1679
0
    return proj_ca;
1680
0
}
1681
1682
//-----------------------------------------------------------------------------
1683
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1684
//-----------------------------------------------------------------------------
1685
1686
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1687
int ImStricmp(const char* str1, const char* str2)
1688
0
{
1689
0
    int d;
1690
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1691
0
    return d;
1692
0
}
1693
1694
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1695
0
{
1696
0
    int d = 0;
1697
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1698
0
    return d;
1699
0
}
1700
1701
void ImStrncpy(char* dst, const char* src, size_t count)
1702
40
{
1703
40
    if (count < 1)
1704
0
        return;
1705
40
    if (count > 1)
1706
40
        strncpy(dst, src, count - 1);
1707
40
    dst[count - 1] = 0;
1708
40
}
1709
1710
char* ImStrdup(const char* str)
1711
3
{
1712
3
    size_t len = strlen(str);
1713
3
    void* buf = IM_ALLOC(len + 1);
1714
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1715
3
}
1716
1717
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1718
0
{
1719
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1720
0
    size_t src_size = strlen(src) + 1;
1721
0
    if (dst_buf_size < src_size)
1722
0
    {
1723
0
        IM_FREE(dst);
1724
0
        dst = (char*)IM_ALLOC(src_size);
1725
0
        if (p_dst_size)
1726
0
            *p_dst_size = src_size;
1727
0
    }
1728
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1729
0
}
1730
1731
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1732
0
{
1733
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1734
0
    return p;
1735
0
}
1736
1737
int ImStrlenW(const ImWchar* str)
1738
0
{
1739
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1740
0
    int n = 0;
1741
0
    while (*str++) n++;
1742
0
    return n;
1743
0
}
1744
1745
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1746
const char* ImStreolRange(const char* str, const char* str_end)
1747
0
{
1748
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1749
0
    return p ? p : str_end;
1750
0
}
1751
1752
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1753
0
{
1754
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1755
0
        buf_mid_line--;
1756
0
    return buf_mid_line;
1757
0
}
1758
1759
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1760
0
{
1761
0
    if (!needle_end)
1762
0
        needle_end = needle + strlen(needle);
1763
1764
0
    const char un0 = (char)ImToUpper(*needle);
1765
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1766
0
    {
1767
0
        if (ImToUpper(*haystack) == un0)
1768
0
        {
1769
0
            const char* b = needle + 1;
1770
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1771
0
                if (ImToUpper(*a) != ImToUpper(*b))
1772
0
                    break;
1773
0
            if (b == needle_end)
1774
0
                return haystack;
1775
0
        }
1776
0
        haystack++;
1777
0
    }
1778
0
    return NULL;
1779
0
}
1780
1781
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1782
void ImStrTrimBlanks(char* buf)
1783
0
{
1784
0
    char* p = buf;
1785
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1786
0
        p++;
1787
0
    char* p_start = p;
1788
0
    while (*p != 0)                         // Find end of string
1789
0
        p++;
1790
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1791
0
        p--;
1792
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1793
0
        memmove(buf, p_start, p - p_start);
1794
0
    buf[p - p_start] = 0;                   // Zero terminate
1795
0
}
1796
1797
const char* ImStrSkipBlank(const char* str)
1798
0
{
1799
0
    while (str[0] == ' ' || str[0] == '\t')
1800
0
        str++;
1801
0
    return str;
1802
0
}
1803
1804
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1805
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1806
// B) When buf==NULL vsnprintf() will return the output size.
1807
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1808
1809
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1810
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1811
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1812
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1813
#ifdef IMGUI_USE_STB_SPRINTF
1814
#define STB_SPRINTF_IMPLEMENTATION
1815
#ifdef IMGUI_STB_SPRINTF_FILENAME
1816
#include IMGUI_STB_SPRINTF_FILENAME
1817
#else
1818
#include "stb_sprintf.h"
1819
#endif
1820
#endif
1821
1822
#if defined(_MSC_VER) && !defined(vsnprintf)
1823
#define vsnprintf _vsnprintf
1824
#endif
1825
1826
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1827
1
{
1828
1
    va_list args;
1829
1
    va_start(args, fmt);
1830
#ifdef IMGUI_USE_STB_SPRINTF
1831
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1832
#else
1833
1
    int w = vsnprintf(buf, buf_size, fmt, args);
1834
1
#endif
1835
1
    va_end(args);
1836
1
    if (buf == NULL)
1837
0
        return w;
1838
1
    if (w == -1 || w >= (int)buf_size)
1839
0
        w = (int)buf_size - 1;
1840
1
    buf[w] = 0;
1841
1
    return w;
1842
1
}
1843
1844
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1845
311
{
1846
#ifdef IMGUI_USE_STB_SPRINTF
1847
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1848
#else
1849
311
    int w = vsnprintf(buf, buf_size, fmt, args);
1850
311
#endif
1851
311
    if (buf == NULL)
1852
0
        return w;
1853
311
    if (w == -1 || w >= (int)buf_size)
1854
0
        w = (int)buf_size - 1;
1855
311
    buf[w] = 0;
1856
311
    return w;
1857
311
}
1858
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1859
1860
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1861
311
{
1862
311
    ImGuiContext& g = *GImGui;
1863
311
    va_list args;
1864
311
    va_start(args, fmt);
1865
311
    int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1866
311
    *out_buf = g.TempBuffer.Data;
1867
311
    if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1868
311
    va_end(args);
1869
311
}
1870
1871
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1872
0
{
1873
0
    ImGuiContext& g = *GImGui;
1874
0
    int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1875
0
    *out_buf = g.TempBuffer.Data;
1876
0
    if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1877
0
}
1878
1879
// CRC32 needs a 1KB lookup table (not cache friendly)
1880
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1881
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1882
static const ImU32 GCrc32LookupTable[256] =
1883
{
1884
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1885
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1886
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1887
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1888
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1889
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1890
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1891
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1892
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1893
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1894
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1895
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1896
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1897
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1898
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1899
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1900
};
1901
1902
// Known size hash
1903
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1904
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1905
ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed)
1906
309
{
1907
309
    ImU32 crc = ~seed;
1908
309
    const unsigned char* data = (const unsigned char*)data_p;
1909
309
    const ImU32* crc32_lut = GCrc32LookupTable;
1910
1.54k
    while (data_size-- != 0)
1911
1.23k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1912
309
    return ~crc;
1913
309
}
1914
1915
// Zero-terminated string hash, with support for ### to reset back to seed value
1916
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
1917
// Because this syntax is rarely used we are optimizing for the common case.
1918
// - If we reach ### in the string we discard the hash so far and reset to the seed.
1919
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
1920
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1921
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
1922
362k
{
1923
362k
    seed = ~seed;
1924
362k
    ImU32 crc = seed;
1925
362k
    const unsigned char* data = (const unsigned char*)data_p;
1926
362k
    const ImU32* crc32_lut = GCrc32LookupTable;
1927
362k
    if (data_size != 0)
1928
0
    {
1929
0
        while (data_size-- != 0)
1930
0
        {
1931
0
            unsigned char c = *data++;
1932
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
1933
0
                crc = seed;
1934
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1935
0
        }
1936
0
    }
1937
362k
    else
1938
362k
    {
1939
4.26M
        while (unsigned char c = *data++)
1940
3.89M
        {
1941
3.89M
            if (c == '#' && data[0] == '#' && data[1] == '#')
1942
0
                crc = seed;
1943
3.89M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1944
3.89M
        }
1945
362k
    }
1946
362k
    return ~crc;
1947
362k
}
1948
1949
//-----------------------------------------------------------------------------
1950
// [SECTION] MISC HELPERS/UTILITIES (File functions)
1951
//-----------------------------------------------------------------------------
1952
1953
// Default file functions
1954
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
1955
1956
ImFileHandle ImFileOpen(const char* filename, const char* mode)
1957
0
{
1958
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
1959
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
1960
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
1961
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
1962
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
1963
    ImVector<ImWchar> buf;
1964
    buf.resize(filename_wsize + mode_wsize);
1965
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
1966
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
1967
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
1968
#else
1969
0
    return fopen(filename, mode);
1970
0
#endif
1971
0
}
1972
1973
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
1974
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
1975
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
1976
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
1977
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
1978
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
1979
1980
// Helper: Load file content into memory
1981
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
1982
// This can't really be used with "rt" because fseek size won't match read size.
1983
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
1984
0
{
1985
0
    IM_ASSERT(filename && mode);
1986
0
    if (out_file_size)
1987
0
        *out_file_size = 0;
1988
1989
0
    ImFileHandle f;
1990
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
1991
0
        return NULL;
1992
1993
0
    size_t file_size = (size_t)ImFileGetSize(f);
1994
0
    if (file_size == (size_t)-1)
1995
0
    {
1996
0
        ImFileClose(f);
1997
0
        return NULL;
1998
0
    }
1999
2000
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2001
0
    if (file_data == NULL)
2002
0
    {
2003
0
        ImFileClose(f);
2004
0
        return NULL;
2005
0
    }
2006
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2007
0
    {
2008
0
        ImFileClose(f);
2009
0
        IM_FREE(file_data);
2010
0
        return NULL;
2011
0
    }
2012
0
    if (padding_bytes > 0)
2013
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2014
2015
0
    ImFileClose(f);
2016
0
    if (out_file_size)
2017
0
        *out_file_size = file_size;
2018
2019
0
    return file_data;
2020
0
}
2021
2022
//-----------------------------------------------------------------------------
2023
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2024
//-----------------------------------------------------------------------------
2025
2026
IM_MSVC_RUNTIME_CHECKS_OFF
2027
2028
// Convert UTF-8 to 32-bit character, process single character input.
2029
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2030
// We handle UTF-8 decoding error by skipping forward.
2031
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2032
802
{
2033
802
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2034
802
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2035
802
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2036
802
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2037
802
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2038
802
    int len = lengths[*(const unsigned char*)in_text >> 3];
2039
802
    int wanted = len + (len ? 0 : 1);
2040
2041
802
    if (in_text_end == NULL)
2042
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2043
2044
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2045
    // so it is fast even with excessive branching.
2046
802
    unsigned char s[4];
2047
802
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2048
802
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2049
802
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2050
802
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2051
2052
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2053
802
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2054
802
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2055
802
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2056
802
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2057
802
    *out_char >>= shiftc[len];
2058
2059
    // Accumulate the various error conditions.
2060
802
    int e = 0;
2061
802
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2062
802
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2063
802
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2064
802
    e |= (s[1] & 0xc0) >> 2;
2065
802
    e |= (s[2] & 0xc0) >> 4;
2066
802
    e |= (s[3]       ) >> 6;
2067
802
    e ^= 0x2a; // top two bits of each tail byte correct?
2068
802
    e >>= shifte[len];
2069
2070
802
    if (e)
2071
292
    {
2072
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2073
        // One byte is consumed in case of invalid first byte of in_text.
2074
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2075
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2076
292
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2077
292
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2078
292
    }
2079
2080
802
    return wanted;
2081
802
}
2082
2083
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2084
0
{
2085
0
    ImWchar* buf_out = buf;
2086
0
    ImWchar* buf_end = buf + buf_size;
2087
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2088
0
    {
2089
0
        unsigned int c;
2090
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2091
0
        *buf_out++ = (ImWchar)c;
2092
0
    }
2093
0
    *buf_out = 0;
2094
0
    if (in_text_remaining)
2095
0
        *in_text_remaining = in_text;
2096
0
    return (int)(buf_out - buf);
2097
0
}
2098
2099
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2100
0
{
2101
0
    int char_count = 0;
2102
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2103
0
    {
2104
0
        unsigned int c;
2105
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2106
0
        char_count++;
2107
0
    }
2108
0
    return char_count;
2109
0
}
2110
2111
// Based on stb_to_utf8() from github.com/nothings/stb/
2112
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2113
0
{
2114
0
    if (c < 0x80)
2115
0
    {
2116
0
        buf[0] = (char)c;
2117
0
        return 1;
2118
0
    }
2119
0
    if (c < 0x800)
2120
0
    {
2121
0
        if (buf_size < 2) return 0;
2122
0
        buf[0] = (char)(0xc0 + (c >> 6));
2123
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2124
0
        return 2;
2125
0
    }
2126
0
    if (c < 0x10000)
2127
0
    {
2128
0
        if (buf_size < 3) return 0;
2129
0
        buf[0] = (char)(0xe0 + (c >> 12));
2130
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2131
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2132
0
        return 3;
2133
0
    }
2134
0
    if (c <= 0x10FFFF)
2135
0
    {
2136
0
        if (buf_size < 4) return 0;
2137
0
        buf[0] = (char)(0xf0 + (c >> 18));
2138
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2139
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2140
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2141
0
        return 4;
2142
0
    }
2143
    // Invalid code point, the max unicode is 0x10FFFF
2144
0
    return 0;
2145
0
}
2146
2147
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2148
0
{
2149
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2150
0
    out_buf[count] = 0;
2151
0
    return out_buf;
2152
0
}
2153
2154
// Not optimal but we very rarely use this function.
2155
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2156
0
{
2157
0
    unsigned int unused = 0;
2158
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2159
0
}
2160
2161
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2162
0
{
2163
0
    if (c < 0x80) return 1;
2164
0
    if (c < 0x800) return 2;
2165
0
    if (c < 0x10000) return 3;
2166
0
    if (c <= 0x10FFFF) return 4;
2167
0
    return 3;
2168
0
}
2169
2170
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2171
0
{
2172
0
    char* buf_p = out_buf;
2173
0
    const char* buf_end = out_buf + out_buf_size;
2174
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2175
0
    {
2176
0
        unsigned int c = (unsigned int)(*in_text++);
2177
0
        if (c < 0x80)
2178
0
            *buf_p++ = (char)c;
2179
0
        else
2180
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2181
0
    }
2182
0
    *buf_p = 0;
2183
0
    return (int)(buf_p - out_buf);
2184
0
}
2185
2186
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2187
0
{
2188
0
    int bytes_count = 0;
2189
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2190
0
    {
2191
0
        unsigned int c = (unsigned int)(*in_text++);
2192
0
        if (c < 0x80)
2193
0
            bytes_count++;
2194
0
        else
2195
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2196
0
    }
2197
0
    return bytes_count;
2198
0
}
2199
IM_MSVC_RUNTIME_CHECKS_RESTORE
2200
2201
//-----------------------------------------------------------------------------
2202
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2203
// Note: The Convert functions are early design which are not consistent with other API.
2204
//-----------------------------------------------------------------------------
2205
2206
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2207
0
{
2208
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2209
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2210
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2211
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2212
0
    return IM_COL32(r, g, b, 0xFF);
2213
0
}
2214
2215
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2216
221k
{
2217
221k
    float s = 1.0f / 255.0f;
2218
221k
    return ImVec4(
2219
221k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2220
221k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2221
221k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2222
221k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2223
221k
}
2224
2225
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2226
1.21M
{
2227
1.21M
    ImU32 out;
2228
1.21M
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2229
1.21M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2230
1.21M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2231
1.21M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2232
1.21M
    return out;
2233
1.21M
}
2234
2235
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2236
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2237
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2238
0
{
2239
0
    float K = 0.f;
2240
0
    if (g < b)
2241
0
    {
2242
0
        ImSwap(g, b);
2243
0
        K = -1.f;
2244
0
    }
2245
0
    if (r < g)
2246
0
    {
2247
0
        ImSwap(r, g);
2248
0
        K = -2.f / 6.f - K;
2249
0
    }
2250
2251
0
    const float chroma = r - (g < b ? g : b);
2252
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2253
0
    out_s = chroma / (r + 1e-20f);
2254
0
    out_v = r;
2255
0
}
2256
2257
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2258
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2259
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2260
0
{
2261
0
    if (s == 0.0f)
2262
0
    {
2263
        // gray
2264
0
        out_r = out_g = out_b = v;
2265
0
        return;
2266
0
    }
2267
2268
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2269
0
    int   i = (int)h;
2270
0
    float f = h - (float)i;
2271
0
    float p = v * (1.0f - s);
2272
0
    float q = v * (1.0f - s * f);
2273
0
    float t = v * (1.0f - s * (1.0f - f));
2274
2275
0
    switch (i)
2276
0
    {
2277
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2278
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2279
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2280
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2281
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2282
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2283
0
    }
2284
0
}
2285
2286
//-----------------------------------------------------------------------------
2287
// [SECTION] ImGuiStorage
2288
// Helper: Key->value storage
2289
//-----------------------------------------------------------------------------
2290
2291
// std::lower_bound but without the bullshit
2292
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2293
180k
{
2294
180k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2295
180k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2296
180k
    size_t count = (size_t)(last - first);
2297
542k
    while (count > 0)
2298
361k
    {
2299
361k
        size_t count2 = count >> 1;
2300
361k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2301
361k
        if (mid->key < key)
2302
90.5k
        {
2303
90.5k
            first = ++mid;
2304
90.5k
            count -= count2 + 1;
2305
90.5k
        }
2306
270k
        else
2307
270k
        {
2308
270k
            count = count2;
2309
270k
        }
2310
361k
    }
2311
180k
    return first;
2312
180k
}
2313
2314
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2315
void ImGuiStorage::BuildSortByKey()
2316
0
{
2317
0
    struct StaticFunc
2318
0
    {
2319
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2320
0
        {
2321
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2322
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2323
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2324
0
            return 0;
2325
0
        }
2326
0
    };
2327
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2328
0
}
2329
2330
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2331
0
{
2332
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2333
0
    if (it == Data.end() || it->key != key)
2334
0
        return default_val;
2335
0
    return it->val_i;
2336
0
}
2337
2338
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2339
0
{
2340
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2341
0
}
2342
2343
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2344
0
{
2345
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2346
0
    if (it == Data.end() || it->key != key)
2347
0
        return default_val;
2348
0
    return it->val_f;
2349
0
}
2350
2351
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2352
180k
{
2353
180k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2354
180k
    if (it == Data.end() || it->key != key)
2355
3
        return NULL;
2356
180k
    return it->val_p;
2357
180k
}
2358
2359
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2360
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2361
0
{
2362
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2363
0
    if (it == Data.end() || it->key != key)
2364
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2365
0
    return &it->val_i;
2366
0
}
2367
2368
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2369
0
{
2370
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2371
0
}
2372
2373
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2374
0
{
2375
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2376
0
    if (it == Data.end() || it->key != key)
2377
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2378
0
    return &it->val_f;
2379
0
}
2380
2381
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2382
0
{
2383
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2384
0
    if (it == Data.end() || it->key != key)
2385
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2386
0
    return &it->val_p;
2387
0
}
2388
2389
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2390
void ImGuiStorage::SetInt(ImGuiID key, int val)
2391
0
{
2392
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2393
0
    if (it == Data.end() || it->key != key)
2394
0
    {
2395
0
        Data.insert(it, ImGuiStoragePair(key, val));
2396
0
        return;
2397
0
    }
2398
0
    it->val_i = val;
2399
0
}
2400
2401
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2402
0
{
2403
0
    SetInt(key, val ? 1 : 0);
2404
0
}
2405
2406
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2407
0
{
2408
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2409
0
    if (it == Data.end() || it->key != key)
2410
0
    {
2411
0
        Data.insert(it, ImGuiStoragePair(key, val));
2412
0
        return;
2413
0
    }
2414
0
    it->val_f = val;
2415
0
}
2416
2417
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2418
3
{
2419
3
    ImGuiStoragePair* it = LowerBound(Data, key);
2420
3
    if (it == Data.end() || it->key != key)
2421
3
    {
2422
3
        Data.insert(it, ImGuiStoragePair(key, val));
2423
3
        return;
2424
3
    }
2425
0
    it->val_p = val;
2426
0
}
2427
2428
void ImGuiStorage::SetAllInt(int v)
2429
0
{
2430
0
    for (int i = 0; i < Data.Size; i++)
2431
0
        Data[i].val_i = v;
2432
0
}
2433
2434
//-----------------------------------------------------------------------------
2435
// [SECTION] ImGuiTextFilter
2436
//-----------------------------------------------------------------------------
2437
2438
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2439
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2440
0
{
2441
0
    InputBuf[0] = 0;
2442
0
    CountGrep = 0;
2443
0
    if (default_filter)
2444
0
    {
2445
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2446
0
        Build();
2447
0
    }
2448
0
}
2449
2450
bool ImGuiTextFilter::Draw(const char* label, float width)
2451
0
{
2452
0
    if (width != 0.0f)
2453
0
        ImGui::SetNextItemWidth(width);
2454
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2455
0
    if (value_changed)
2456
0
        Build();
2457
0
    return value_changed;
2458
0
}
2459
2460
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2461
0
{
2462
0
    out->resize(0);
2463
0
    const char* wb = b;
2464
0
    const char* we = wb;
2465
0
    while (we < e)
2466
0
    {
2467
0
        if (*we == separator)
2468
0
        {
2469
0
            out->push_back(ImGuiTextRange(wb, we));
2470
0
            wb = we + 1;
2471
0
        }
2472
0
        we++;
2473
0
    }
2474
0
    if (wb != we)
2475
0
        out->push_back(ImGuiTextRange(wb, we));
2476
0
}
2477
2478
void ImGuiTextFilter::Build()
2479
0
{
2480
0
    Filters.resize(0);
2481
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2482
0
    input_range.split(',', &Filters);
2483
2484
0
    CountGrep = 0;
2485
0
    for (int i = 0; i != Filters.Size; i++)
2486
0
    {
2487
0
        ImGuiTextRange& f = Filters[i];
2488
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2489
0
            f.b++;
2490
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2491
0
            f.e--;
2492
0
        if (f.empty())
2493
0
            continue;
2494
0
        if (Filters[i].b[0] != '-')
2495
0
            CountGrep += 1;
2496
0
    }
2497
0
}
2498
2499
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2500
0
{
2501
0
    if (Filters.empty())
2502
0
        return true;
2503
2504
0
    if (text == NULL)
2505
0
        text = "";
2506
2507
0
    for (int i = 0; i != Filters.Size; i++)
2508
0
    {
2509
0
        const ImGuiTextRange& f = Filters[i];
2510
0
        if (f.empty())
2511
0
            continue;
2512
0
        if (f.b[0] == '-')
2513
0
        {
2514
            // Subtract
2515
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2516
0
                return false;
2517
0
        }
2518
0
        else
2519
0
        {
2520
            // Grep
2521
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2522
0
                return true;
2523
0
        }
2524
0
    }
2525
2526
    // Implicit * grep
2527
0
    if (CountGrep == 0)
2528
0
        return true;
2529
2530
0
    return false;
2531
0
}
2532
2533
//-----------------------------------------------------------------------------
2534
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2535
//-----------------------------------------------------------------------------
2536
2537
// On some platform vsnprintf() takes va_list by reference and modifies it.
2538
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2539
#ifndef va_copy
2540
#if defined(__GNUC__) || defined(__clang__)
2541
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2542
#else
2543
#define va_copy(dest, src) (dest = src)
2544
#endif
2545
#endif
2546
2547
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2548
2549
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2550
0
{
2551
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2552
2553
    // Add zero-terminator the first time
2554
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2555
0
    const int needed_sz = write_off + len;
2556
0
    if (write_off + len >= Buf.Capacity)
2557
0
    {
2558
0
        int new_capacity = Buf.Capacity * 2;
2559
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2560
0
    }
2561
2562
0
    Buf.resize(needed_sz);
2563
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2564
0
    Buf[write_off - 1 + len] = 0;
2565
0
}
2566
2567
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2568
0
{
2569
0
    va_list args;
2570
0
    va_start(args, fmt);
2571
0
    appendfv(fmt, args);
2572
0
    va_end(args);
2573
0
}
2574
2575
// Helper: Text buffer for logging/accumulating text
2576
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2577
0
{
2578
0
    va_list args_copy;
2579
0
    va_copy(args_copy, args);
2580
2581
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2582
0
    if (len <= 0)
2583
0
    {
2584
0
        va_end(args_copy);
2585
0
        return;
2586
0
    }
2587
2588
    // Add zero-terminator the first time
2589
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2590
0
    const int needed_sz = write_off + len;
2591
0
    if (write_off + len >= Buf.Capacity)
2592
0
    {
2593
0
        int new_capacity = Buf.Capacity * 2;
2594
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2595
0
    }
2596
2597
0
    Buf.resize(needed_sz);
2598
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2599
0
    va_end(args_copy);
2600
0
}
2601
2602
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2603
0
{
2604
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2605
0
    if (old_size == new_size)
2606
0
        return;
2607
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2608
0
        LineOffsets.push_back(EndOffset);
2609
0
    const char* base_end = base + new_size;
2610
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2611
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2612
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2613
0
    EndOffset = ImMax(EndOffset, new_size);
2614
0
}
2615
2616
//-----------------------------------------------------------------------------
2617
// [SECTION] ImGuiListClipper
2618
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
2619
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
2620
//-----------------------------------------------------------------------------
2621
2622
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2623
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2624
static bool GetSkipItemForListClipping()
2625
0
{
2626
0
    ImGuiContext& g = *GImGui;
2627
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2628
0
}
2629
2630
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2631
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2632
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2633
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2634
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2635
{
2636
    ImGuiContext& g = *GImGui;
2637
    ImGuiWindow* window = g.CurrentWindow;
2638
    if (g.LogEnabled)
2639
    {
2640
        // If logging is active, do not perform any clipping
2641
        *out_items_display_start = 0;
2642
        *out_items_display_end = items_count;
2643
        return;
2644
    }
2645
    if (GetSkipItemForListClipping())
2646
    {
2647
        *out_items_display_start = *out_items_display_end = 0;
2648
        return;
2649
    }
2650
2651
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2652
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2653
    ImRect rect = window->ClipRect;
2654
    if (g.NavMoveScoringItems)
2655
        rect.Add(g.NavScoringNoClipRect);
2656
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2657
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2658
2659
    const ImVec2 pos = window->DC.CursorPos;
2660
    int start = (int)((rect.Min.y - pos.y) / items_height);
2661
    int end = (int)((rect.Max.y - pos.y) / items_height);
2662
2663
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2664
    // FIXME: Verify this works with tabbing
2665
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2666
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2667
        start--;
2668
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2669
        end++;
2670
2671
    start = ImClamp(start, 0, items_count);
2672
    end = ImClamp(end + 1, start, items_count);
2673
    *out_items_display_start = start;
2674
    *out_items_display_end = end;
2675
}
2676
#endif
2677
2678
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2679
0
{
2680
0
    if (ranges.Size - offset <= 1)
2681
0
        return;
2682
2683
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2684
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2685
0
        for (int i = offset; i < sort_end + offset; ++i)
2686
0
            if (ranges[i].Min > ranges[i + 1].Min)
2687
0
                ImSwap(ranges[i], ranges[i + 1]);
2688
2689
    // Now fuse ranges together as much as possible.
2690
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2691
0
    {
2692
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2693
0
        if (ranges[i - 1].Max < ranges[i].Min)
2694
0
            continue;
2695
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2696
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2697
0
        ranges.erase(ranges.Data + i);
2698
0
        i--;
2699
0
    }
2700
0
}
2701
2702
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2703
0
{
2704
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2705
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2706
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2707
0
    ImGuiContext& g = *GImGui;
2708
0
    ImGuiWindow* window = g.CurrentWindow;
2709
0
    float off_y = pos_y - window->DC.CursorPos.y;
2710
0
    window->DC.CursorPos.y = pos_y;
2711
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2712
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2713
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2714
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2715
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2716
0
    if (ImGuiTable* table = g.CurrentTable)
2717
0
    {
2718
0
        if (table->IsInsideRow)
2719
0
            ImGui::TableEndRow(table);
2720
0
        table->RowPosY2 = window->DC.CursorPos.y;
2721
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2722
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2723
0
        table->RowBgColorCounter += row_increase;
2724
0
    }
2725
0
}
2726
2727
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2728
0
{
2729
    // StartPosY starts from ItemsFrozen hence the subtraction
2730
    // Perform the add and multiply with double to allow seeking through larger ranges
2731
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2732
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2733
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2734
0
}
2735
2736
ImGuiListClipper::ImGuiListClipper()
2737
0
{
2738
0
    memset(this, 0, sizeof(*this));
2739
0
    ItemsCount = -1;
2740
0
}
2741
2742
ImGuiListClipper::~ImGuiListClipper()
2743
0
{
2744
0
    End();
2745
0
}
2746
2747
void ImGuiListClipper::Begin(int items_count, float items_height)
2748
0
{
2749
0
    ImGuiContext& g = *GImGui;
2750
0
    ImGuiWindow* window = g.CurrentWindow;
2751
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2752
2753
0
    if (ImGuiTable* table = g.CurrentTable)
2754
0
        if (table->IsInsideRow)
2755
0
            ImGui::TableEndRow(table);
2756
2757
0
    StartPosY = window->DC.CursorPos.y;
2758
0
    ItemsHeight = items_height;
2759
0
    ItemsCount = items_count;
2760
0
    DisplayStart = -1;
2761
0
    DisplayEnd = 0;
2762
2763
    // Acquire temporary buffer
2764
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2765
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2766
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2767
0
    data->Reset(this);
2768
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2769
0
    TempData = data;
2770
0
}
2771
2772
void ImGuiListClipper::End()
2773
0
{
2774
0
    ImGuiContext& g = *GImGui;
2775
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2776
0
    {
2777
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2778
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2779
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2780
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2781
2782
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2783
0
        IM_ASSERT(data->ListClipper == this);
2784
0
        data->StepNo = data->Ranges.Size;
2785
0
        if (--g.ClipperTempDataStacked > 0)
2786
0
        {
2787
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2788
0
            data->ListClipper->TempData = data;
2789
0
        }
2790
0
        TempData = NULL;
2791
0
    }
2792
0
    ItemsCount = -1;
2793
0
}
2794
2795
void ImGuiListClipper::ForceDisplayRangeByIndices(int item_min, int item_max)
2796
0
{
2797
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2798
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2799
0
    IM_ASSERT(item_min <= item_max);
2800
0
    if (item_min < item_max)
2801
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_min, item_max));
2802
0
}
2803
2804
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2805
0
{
2806
0
    ImGuiContext& g = *GImGui;
2807
0
    ImGuiWindow* window = g.CurrentWindow;
2808
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2809
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2810
2811
0
    ImGuiTable* table = g.CurrentTable;
2812
0
    if (table && table->IsInsideRow)
2813
0
        ImGui::TableEndRow(table);
2814
2815
    // No items
2816
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2817
0
        return false;
2818
2819
    // While we are in frozen row state, keep displaying items one by one, unclipped
2820
    // FIXME: Could be stored as a table-agnostic state.
2821
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2822
0
    {
2823
0
        clipper->DisplayStart = data->ItemsFrozen;
2824
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2825
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2826
0
            data->ItemsFrozen++;
2827
0
        return true;
2828
0
    }
2829
2830
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2831
0
    bool calc_clipping = false;
2832
0
    if (data->StepNo == 0)
2833
0
    {
2834
0
        clipper->StartPosY = window->DC.CursorPos.y;
2835
0
        if (clipper->ItemsHeight <= 0.0f)
2836
0
        {
2837
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2838
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2839
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2840
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2841
0
            data->StepNo = 1;
2842
0
            return true;
2843
0
        }
2844
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2845
0
    }
2846
2847
    // Step 1: Let the clipper infer height from first range
2848
0
    if (clipper->ItemsHeight <= 0.0f)
2849
0
    {
2850
0
        IM_ASSERT(data->StepNo == 1);
2851
0
        if (table)
2852
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2853
2854
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2855
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2856
0
        if (affected_by_floating_point_precision)
2857
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2858
2859
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2860
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
2861
0
    }
2862
2863
    // Step 0 or 1: Calculate the actual ranges of visible elements.
2864
0
    const int already_submitted = clipper->DisplayEnd;
2865
0
    if (calc_clipping)
2866
0
    {
2867
0
        if (g.LogEnabled)
2868
0
        {
2869
            // If logging is active, do not perform any clipping
2870
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2871
0
        }
2872
0
        else
2873
0
        {
2874
            // Add range selected to be included for navigation
2875
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2876
0
            if (is_nav_request)
2877
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
2878
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)
2879
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
2880
2881
            // Add focused/active item
2882
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
2883
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
2884
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
2885
2886
            // Add visible range
2887
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
2888
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
2889
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
2890
0
        }
2891
2892
        // Convert position ranges to item index ranges
2893
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
2894
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
2895
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
2896
0
        for (int i = 0; i < data->Ranges.Size; i++)
2897
0
            if (data->Ranges[i].PosToIndexConvert)
2898
0
            {
2899
0
                int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
2900
0
                int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
2901
0
                data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
2902
0
                data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, clipper->ItemsCount);
2903
0
                data->Ranges[i].PosToIndexConvert = false;
2904
0
            }
2905
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
2906
0
    }
2907
2908
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
2909
0
    if (data->StepNo < data->Ranges.Size)
2910
0
    {
2911
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
2912
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
2913
0
        if (clipper->DisplayStart > already_submitted) //-V1051
2914
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
2915
0
        data->StepNo++;
2916
0
        return true;
2917
0
    }
2918
2919
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
2920
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
2921
0
    if (clipper->ItemsCount < INT_MAX)
2922
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
2923
2924
0
    return false;
2925
0
}
2926
2927
bool ImGuiListClipper::Step()
2928
0
{
2929
0
    ImGuiContext& g = *GImGui;
2930
0
    bool need_items_height = (ItemsHeight <= 0.0f);
2931
0
    bool ret = ImGuiListClipper_StepInternal(this);
2932
0
    if (ret && (DisplayStart == DisplayEnd))
2933
0
        ret = false;
2934
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
2935
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
2936
0
    if (need_items_height && ItemsHeight > 0.0f)
2937
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
2938
0
    if (ret)
2939
0
    {
2940
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
2941
0
    }
2942
0
    else
2943
0
    {
2944
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
2945
0
        End();
2946
0
    }
2947
0
    return ret;
2948
0
}
2949
2950
//-----------------------------------------------------------------------------
2951
// [SECTION] STYLING
2952
//-----------------------------------------------------------------------------
2953
2954
ImGuiStyle& ImGui::GetStyle()
2955
130k
{
2956
130k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
2957
130k
    return GImGui->Style;
2958
130k
}
2959
2960
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
2961
1.08M
{
2962
1.08M
    ImGuiStyle& style = GImGui->Style;
2963
1.08M
    ImVec4 c = style.Colors[idx];
2964
1.08M
    c.w *= style.Alpha * alpha_mul;
2965
1.08M
    return ColorConvertFloat4ToU32(c);
2966
1.08M
}
2967
2968
ImU32 ImGui::GetColorU32(const ImVec4& col)
2969
0
{
2970
0
    ImGuiStyle& style = GImGui->Style;
2971
0
    ImVec4 c = col;
2972
0
    c.w *= style.Alpha;
2973
0
    return ColorConvertFloat4ToU32(c);
2974
0
}
2975
2976
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
2977
0
{
2978
0
    ImGuiStyle& style = GImGui->Style;
2979
0
    return style.Colors[idx];
2980
0
}
2981
2982
ImU32 ImGui::GetColorU32(ImU32 col)
2983
0
{
2984
0
    ImGuiStyle& style = GImGui->Style;
2985
0
    if (style.Alpha >= 1.0f)
2986
0
        return col;
2987
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
2988
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
2989
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
2990
0
}
2991
2992
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
2993
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
2994
0
{
2995
0
    ImGuiContext& g = *GImGui;
2996
0
    ImGuiColorMod backup;
2997
0
    backup.Col = idx;
2998
0
    backup.BackupValue = g.Style.Colors[idx];
2999
0
    g.ColorStack.push_back(backup);
3000
0
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3001
0
}
3002
3003
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3004
90.2k
{
3005
90.2k
    ImGuiContext& g = *GImGui;
3006
90.2k
    ImGuiColorMod backup;
3007
90.2k
    backup.Col = idx;
3008
90.2k
    backup.BackupValue = g.Style.Colors[idx];
3009
90.2k
    g.ColorStack.push_back(backup);
3010
90.2k
    g.Style.Colors[idx] = col;
3011
90.2k
}
3012
3013
void ImGui::PopStyleColor(int count)
3014
90.2k
{
3015
90.2k
    ImGuiContext& g = *GImGui;
3016
90.2k
    if (g.ColorStack.Size < count)
3017
0
    {
3018
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3019
0
        count = g.ColorStack.Size;
3020
0
    }
3021
180k
    while (count > 0)
3022
90.2k
    {
3023
90.2k
        ImGuiColorMod& backup = g.ColorStack.back();
3024
90.2k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3025
90.2k
        g.ColorStack.pop_back();
3026
90.2k
        count--;
3027
90.2k
    }
3028
90.2k
}
3029
3030
struct ImGuiStyleVarInfo
3031
{
3032
    ImGuiDataType   Type;
3033
    ImU32           Count;
3034
    ImU32           Offset;
3035
180k
    void*           GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
3036
};
3037
3038
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3039
{
3040
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3041
};
3042
3043
static const ImGuiStyleVarInfo GStyleVarInfo[] =
3044
{
3045
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
3046
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
3047
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
3048
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
3049
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
3050
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
3051
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
3052
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
3053
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
3054
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
3055
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
3056
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
3057
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
3058
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
3059
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
3060
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
3061
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
3062
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
3063
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
3064
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
3065
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
3066
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
3067
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
3068
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
3069
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3070
};
3071
3072
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
3073
180k
{
3074
180k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3075
180k
    IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3076
180k
    return &GStyleVarInfo[idx];
3077
180k
}
3078
3079
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3080
0
{
3081
0
    const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3082
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3083
0
    {
3084
0
        ImGuiContext& g = *GImGui;
3085
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3086
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3087
0
        *pvar = val;
3088
0
        return;
3089
0
    }
3090
0
    IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
3091
0
}
3092
3093
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3094
90.2k
{
3095
90.2k
    const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3096
90.2k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3097
90.2k
    {
3098
90.2k
        ImGuiContext& g = *GImGui;
3099
90.2k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3100
90.2k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3101
90.2k
        *pvar = val;
3102
90.2k
        return;
3103
90.2k
    }
3104
0
    IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
3105
0
}
3106
3107
void ImGui::PopStyleVar(int count)
3108
90.2k
{
3109
90.2k
    ImGuiContext& g = *GImGui;
3110
90.2k
    if (g.StyleVarStack.Size < count)
3111
0
    {
3112
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3113
0
        count = g.StyleVarStack.Size;
3114
0
    }
3115
180k
    while (count > 0)
3116
90.2k
    {
3117
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3118
90.2k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3119
90.2k
        const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3120
90.2k
        void* data = info->GetVarPtr(&g.Style);
3121
90.2k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3122
90.2k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3123
90.2k
        g.StyleVarStack.pop_back();
3124
90.2k
        count--;
3125
90.2k
    }
3126
90.2k
}
3127
3128
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3129
0
{
3130
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3131
0
    switch (idx)
3132
0
    {
3133
0
    case ImGuiCol_Text: return "Text";
3134
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3135
0
    case ImGuiCol_WindowBg: return "WindowBg";
3136
0
    case ImGuiCol_ChildBg: return "ChildBg";
3137
0
    case ImGuiCol_PopupBg: return "PopupBg";
3138
0
    case ImGuiCol_Border: return "Border";
3139
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3140
0
    case ImGuiCol_FrameBg: return "FrameBg";
3141
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3142
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3143
0
    case ImGuiCol_TitleBg: return "TitleBg";
3144
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3145
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3146
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3147
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3148
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3149
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3150
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3151
0
    case ImGuiCol_CheckMark: return "CheckMark";
3152
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3153
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3154
0
    case ImGuiCol_Button: return "Button";
3155
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3156
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3157
0
    case ImGuiCol_Header: return "Header";
3158
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3159
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3160
0
    case ImGuiCol_Separator: return "Separator";
3161
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3162
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3163
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3164
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3165
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3166
0
    case ImGuiCol_Tab: return "Tab";
3167
0
    case ImGuiCol_TabHovered: return "TabHovered";
3168
0
    case ImGuiCol_TabActive: return "TabActive";
3169
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3170
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3171
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3172
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3173
0
    case ImGuiCol_PlotLines: return "PlotLines";
3174
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3175
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3176
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3177
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3178
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3179
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3180
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3181
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3182
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3183
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3184
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3185
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3186
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3187
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3188
0
    }
3189
0
    IM_ASSERT(0);
3190
0
    return "Unknown";
3191
0
}
3192
3193
3194
//-----------------------------------------------------------------------------
3195
// [SECTION] RENDER HELPERS
3196
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3197
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3198
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3199
//-----------------------------------------------------------------------------
3200
3201
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3202
360k
{
3203
360k
    const char* text_display_end = text;
3204
360k
    if (!text_end)
3205
360k
        text_end = (const char*)-1;
3206
3207
3.24M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3208
2.88M
        text_display_end++;
3209
360k
    return text_display_end;
3210
360k
}
3211
3212
// Internal ImGui functions to render text
3213
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3214
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3215
0
{
3216
0
    ImGuiContext& g = *GImGui;
3217
0
    ImGuiWindow* window = g.CurrentWindow;
3218
3219
    // Hide anything after a '##' string
3220
0
    const char* text_display_end;
3221
0
    if (hide_text_after_hash)
3222
0
    {
3223
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3224
0
    }
3225
0
    else
3226
0
    {
3227
0
        if (!text_end)
3228
0
            text_end = text + strlen(text); // FIXME-OPT
3229
0
        text_display_end = text_end;
3230
0
    }
3231
3232
0
    if (text != text_display_end)
3233
0
    {
3234
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3235
0
        if (g.LogEnabled)
3236
0
            LogRenderedText(&pos, text, text_display_end);
3237
0
    }
3238
0
}
3239
3240
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3241
0
{
3242
0
    ImGuiContext& g = *GImGui;
3243
0
    ImGuiWindow* window = g.CurrentWindow;
3244
3245
0
    if (!text_end)
3246
0
        text_end = text + strlen(text); // FIXME-OPT
3247
3248
0
    if (text != text_end)
3249
0
    {
3250
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3251
0
        if (g.LogEnabled)
3252
0
            LogRenderedText(&pos, text, text_end);
3253
0
    }
3254
0
}
3255
3256
// Default clip_rect uses (pos_min,pos_max)
3257
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3258
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3259
180k
{
3260
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3261
180k
    ImVec2 pos = pos_min;
3262
180k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3263
3264
180k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3265
180k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3266
180k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3267
180k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3268
180k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3269
3270
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3271
180k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3272
180k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3273
3274
    // Render
3275
180k
    if (need_clipping)
3276
90.2k
    {
3277
90.2k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3278
90.2k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3279
90.2k
    }
3280
90.2k
    else
3281
90.2k
    {
3282
90.2k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3283
90.2k
    }
3284
180k
}
3285
3286
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3287
180k
{
3288
    // Hide anything after a '##' string
3289
180k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3290
180k
    const int text_len = (int)(text_display_end - text);
3291
180k
    if (text_len == 0)
3292
0
        return;
3293
3294
180k
    ImGuiContext& g = *GImGui;
3295
180k
    ImGuiWindow* window = g.CurrentWindow;
3296
180k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3297
180k
    if (g.LogEnabled)
3298
0
        LogRenderedText(&pos_min, text, text_display_end);
3299
180k
}
3300
3301
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3302
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3303
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3304
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3305
0
{
3306
0
    ImGuiContext& g = *GImGui;
3307
0
    if (text_end_full == NULL)
3308
0
        text_end_full = FindRenderedTextEnd(text);
3309
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3310
3311
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3312
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3313
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3314
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3315
0
    if (text_size.x > pos_max.x - pos_min.x)
3316
0
    {
3317
        // Hello wo...
3318
        // |       |   |
3319
        // min   max   ellipsis_max
3320
        //          <-> this is generally some padding value
3321
3322
0
        const ImFont* font = draw_list->_Data->Font;
3323
0
        const float font_size = draw_list->_Data->FontSize;
3324
0
        const float font_scale = font_size / font->FontSize;
3325
0
        const char* text_end_ellipsis = NULL;
3326
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3327
3328
        // We can now claim the space between pos_max.x and ellipsis_max.x
3329
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3330
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3331
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3332
0
        {
3333
            // Always display at least 1 character if there's no room for character + ellipsis
3334
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3335
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3336
0
        }
3337
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3338
0
        {
3339
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3340
0
            text_end_ellipsis--;
3341
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3342
0
        }
3343
3344
        // Render text, render ellipsis
3345
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3346
0
        ImVec2 ellipsis_pos = ImFloor(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3347
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3348
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3349
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3350
0
    }
3351
0
    else
3352
0
    {
3353
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3354
0
    }
3355
3356
0
    if (g.LogEnabled)
3357
0
        LogRenderedText(&pos_min, text, text_end_full);
3358
0
}
3359
3360
// Render a rectangle shaped with optional rounding and borders
3361
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3362
89.9k
{
3363
89.9k
    ImGuiContext& g = *GImGui;
3364
89.9k
    ImGuiWindow* window = g.CurrentWindow;
3365
89.9k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3366
89.9k
    const float border_size = g.Style.FrameBorderSize;
3367
89.9k
    if (border && border_size > 0.0f)
3368
89.9k
    {
3369
89.9k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3370
89.9k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3371
89.9k
    }
3372
89.9k
}
3373
3374
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3375
0
{
3376
0
    ImGuiContext& g = *GImGui;
3377
0
    ImGuiWindow* window = g.CurrentWindow;
3378
0
    const float border_size = g.Style.FrameBorderSize;
3379
0
    if (border_size > 0.0f)
3380
0
    {
3381
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3382
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3383
0
    }
3384
0
}
3385
3386
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3387
154
{
3388
154
    ImGuiContext& g = *GImGui;
3389
154
    if (id != g.NavId)
3390
79
        return;
3391
75
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3392
11
        return;
3393
64
    ImGuiWindow* window = g.CurrentWindow;
3394
64
    if (window->DC.NavHideHighlightOneFrame)
3395
0
        return;
3396
3397
64
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3398
64
    ImRect display_rect = bb;
3399
64
    display_rect.ClipWith(window->ClipRect);
3400
64
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3401
0
    {
3402
0
        const float THICKNESS = 2.0f;
3403
0
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3404
0
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3405
0
        bool fully_visible = window->ClipRect.Contains(display_rect);
3406
0
        if (!fully_visible)
3407
0
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3408
0
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3409
0
        if (!fully_visible)
3410
0
            window->DrawList->PopClipRect();
3411
0
    }
3412
64
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3413
64
    {
3414
64
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3415
64
    }
3416
64
}
3417
3418
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3419
0
{
3420
0
    ImGuiContext& g = *GImGui;
3421
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3422
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3423
0
    for (int n = 0; n < g.Viewports.Size; n++)
3424
0
    {
3425
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3426
0
        ImVec2 offset, size, uv[4];
3427
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3428
0
            continue;
3429
0
        ImGuiViewportP* viewport = g.Viewports[n];
3430
0
        const ImVec2 pos = base_pos - offset;
3431
0
        const float scale = base_scale * viewport->DpiScale;
3432
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3433
0
            continue;
3434
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3435
0
        ImTextureID tex_id = font_atlas->TexID;
3436
0
        draw_list->PushTextureID(tex_id);
3437
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3438
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3439
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3440
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3441
0
        draw_list->PopTextureID();
3442
0
    }
3443
0
}
3444
3445
//-----------------------------------------------------------------------------
3446
// [SECTION] INITIALIZATION, SHUTDOWN
3447
//-----------------------------------------------------------------------------
3448
3449
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3450
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3451
ImGuiContext* ImGui::GetCurrentContext()
3452
1
{
3453
1
    return GImGui;
3454
1
}
3455
3456
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3457
1
{
3458
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3459
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3460
#else
3461
1
    GImGui = ctx;
3462
1
#endif
3463
1
}
3464
3465
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3466
0
{
3467
0
    GImAllocatorAllocFunc = alloc_func;
3468
0
    GImAllocatorFreeFunc = free_func;
3469
0
    GImAllocatorUserData = user_data;
3470
0
}
3471
3472
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3473
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3474
0
{
3475
0
    *p_alloc_func = GImAllocatorAllocFunc;
3476
0
    *p_free_func = GImAllocatorFreeFunc;
3477
0
    *p_user_data = GImAllocatorUserData;
3478
0
}
3479
3480
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3481
1
{
3482
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3483
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3484
1
    SetCurrentContext(ctx);
3485
1
    Initialize();
3486
1
    if (prev_ctx != NULL)
3487
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3488
1
    return ctx;
3489
1
}
3490
3491
void ImGui::DestroyContext(ImGuiContext* ctx)
3492
0
{
3493
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3494
0
    if (ctx == NULL) //-V1051
3495
0
        ctx = prev_ctx;
3496
0
    SetCurrentContext(ctx);
3497
0
    Shutdown();
3498
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3499
0
    IM_DELETE(ctx);
3500
0
}
3501
3502
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3503
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3504
{
3505
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3506
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3507
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3508
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3509
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3510
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3511
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3512
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3513
};
3514
3515
void ImGui::Initialize()
3516
1
{
3517
1
    ImGuiContext& g = *GImGui;
3518
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3519
3520
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3521
1
    {
3522
1
        ImGuiSettingsHandler ini_handler;
3523
1
        ini_handler.TypeName = "Window";
3524
1
        ini_handler.TypeHash = ImHashStr("Window");
3525
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3526
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3527
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3528
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3529
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3530
1
        AddSettingsHandler(&ini_handler);
3531
1
    }
3532
1
    TableSettingsAddSettingsHandler();
3533
3534
    // Setup default localization table
3535
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3536
3537
    // Create default viewport
3538
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3539
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3540
1
    viewport->Idx = 0;
3541
1
    viewport->PlatformWindowCreated = true;
3542
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3543
1
    g.Viewports.push_back(viewport);
3544
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3545
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3546
3547
1
#ifdef IMGUI_HAS_DOCK
3548
    // Initialize Docking
3549
1
    DockContextInitialize(&g);
3550
1
#endif
3551
3552
1
    g.Initialized = true;
3553
1
}
3554
3555
// This function is merely here to free heap allocations.
3556
void ImGui::Shutdown()
3557
0
{
3558
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3559
0
    ImGuiContext& g = *GImGui;
3560
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3561
0
    {
3562
0
        g.IO.Fonts->Locked = false;
3563
0
        IM_DELETE(g.IO.Fonts);
3564
0
    }
3565
0
    g.IO.Fonts = NULL;
3566
0
    g.DrawListSharedData.TempBuffer.clear();
3567
3568
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3569
0
    if (!g.Initialized)
3570
0
        return;
3571
3572
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3573
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3574
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3575
3576
    // Destroy platform windows
3577
0
    DestroyPlatformWindows();
3578
3579
    // Shutdown extensions
3580
0
    DockContextShutdown(&g);
3581
3582
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3583
3584
    // Clear everything else
3585
0
    g.Windows.clear_delete();
3586
0
    g.WindowsFocusOrder.clear();
3587
0
    g.WindowsTempSortBuffer.clear();
3588
0
    g.CurrentWindow = NULL;
3589
0
    g.CurrentWindowStack.clear();
3590
0
    g.WindowsById.Clear();
3591
0
    g.NavWindow = NULL;
3592
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3593
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3594
0
    g.MovingWindow = NULL;
3595
3596
0
    g.KeysRoutingTable.Clear();
3597
3598
0
    g.ColorStack.clear();
3599
0
    g.StyleVarStack.clear();
3600
0
    g.FontStack.clear();
3601
0
    g.OpenPopupStack.clear();
3602
0
    g.BeginPopupStack.clear();
3603
3604
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3605
0
    g.Viewports.clear_delete();
3606
3607
0
    g.TabBars.Clear();
3608
0
    g.CurrentTabBarStack.clear();
3609
0
    g.ShrinkWidthBuffer.clear();
3610
3611
0
    g.ClipperTempData.clear_destruct();
3612
3613
0
    g.Tables.Clear();
3614
0
    g.TablesTempData.clear_destruct();
3615
0
    g.DrawChannelsTempMergeBuffer.clear();
3616
3617
0
    g.ClipboardHandlerData.clear();
3618
0
    g.MenusIdSubmittedThisFrame.clear();
3619
0
    g.InputTextState.ClearFreeMemory();
3620
3621
0
    g.SettingsWindows.clear();
3622
0
    g.SettingsHandlers.clear();
3623
3624
0
    if (g.LogFile)
3625
0
    {
3626
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3627
0
        if (g.LogFile != stdout)
3628
0
#endif
3629
0
            ImFileClose(g.LogFile);
3630
0
        g.LogFile = NULL;
3631
0
    }
3632
0
    g.LogBuffer.clear();
3633
0
    g.DebugLogBuf.clear();
3634
0
    g.DebugLogIndex.clear();
3635
3636
0
    g.Initialized = false;
3637
0
}
3638
3639
// No specific ordering/dependency support, will see as needed
3640
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3641
0
{
3642
0
    ImGuiContext& g = *ctx;
3643
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3644
0
    g.Hooks.push_back(*hook);
3645
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3646
0
    return g.HookIdNext;
3647
0
}
3648
3649
// Deferred removal, avoiding issue with changing vector while iterating it
3650
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3651
0
{
3652
0
    ImGuiContext& g = *ctx;
3653
0
    IM_ASSERT(hook_id != 0);
3654
0
    for (int n = 0; n < g.Hooks.Size; n++)
3655
0
        if (g.Hooks[n].HookId == hook_id)
3656
0
            g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
3657
0
}
3658
3659
// Call context hooks (used by e.g. test engine)
3660
// We assume a small number of hooks so all stored in same array
3661
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3662
541k
{
3663
541k
    ImGuiContext& g = *ctx;
3664
541k
    for (int n = 0; n < g.Hooks.Size; n++)
3665
0
        if (g.Hooks[n].Type == hook_type)
3666
0
            g.Hooks[n].Callback(&g, &g.Hooks[n]);
3667
541k
}
3668
3669
3670
//-----------------------------------------------------------------------------
3671
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3672
//-----------------------------------------------------------------------------
3673
3674
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3675
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)
3676
3
{
3677
3
    memset(this, 0, sizeof(*this));
3678
3
    Name = ImStrdup(name);
3679
3
    NameBufLen = (int)strlen(name) + 1;
3680
3
    ID = ImHashStr(name);
3681
3
    IDStack.push_back(ID);
3682
3
    ViewportAllowPlatformMonitorExtend = -1;
3683
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3684
3
    MoveId = GetID("#MOVE");
3685
3
    TabId = GetID("#TAB");
3686
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3687
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3688
3
    AutoFitFramesX = AutoFitFramesY = -1;
3689
3
    AutoPosLastDirection = ImGuiDir_None;
3690
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
3691
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3692
3
    LastFrameActive = -1;
3693
3
    LastFrameJustFocused = -1;
3694
3
    LastTimeActive = -1.0f;
3695
3
    FontWindowScale = FontDpiScale = 1.0f;
3696
3
    SettingsOffset = -1;
3697
3
    DockOrder = -1;
3698
3
    DrawList = &DrawListInst;
3699
3
    DrawList->_Data = &context->DrawListSharedData;
3700
3
    DrawList->_OwnerName = Name;
3701
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3702
3
}
3703
3704
ImGuiWindow::~ImGuiWindow()
3705
0
{
3706
0
    IM_ASSERT(DrawList == &DrawListInst);
3707
0
    IM_DELETE(Name);
3708
0
    ColumnsStorage.clear_destruct();
3709
0
}
3710
3711
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3712
181k
{
3713
181k
    ImGuiID seed = IDStack.back();
3714
181k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3715
181k
    ImGuiContext& g = *GImGui;
3716
181k
    if (g.DebugHookIdInfo == id)
3717
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3718
181k
    return id;
3719
181k
}
3720
3721
ImGuiID ImGuiWindow::GetID(const void* ptr)
3722
0
{
3723
0
    ImGuiID seed = IDStack.back();
3724
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3725
0
    ImGuiContext& g = *GImGui;
3726
0
    if (g.DebugHookIdInfo == id)
3727
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3728
0
    return id;
3729
0
}
3730
3731
ImGuiID ImGuiWindow::GetID(int n)
3732
309
{
3733
309
    ImGuiID seed = IDStack.back();
3734
309
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3735
309
    ImGuiContext& g = *GImGui;
3736
309
    if (g.DebugHookIdInfo == id)
3737
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3738
309
    return id;
3739
309
}
3740
3741
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3742
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3743
0
{
3744
0
    ImGuiID seed = IDStack.back();
3745
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3746
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3747
0
    return id;
3748
0
}
3749
3750
static void SetCurrentWindow(ImGuiWindow* window)
3751
361k
{
3752
361k
    ImGuiContext& g = *GImGui;
3753
361k
    g.CurrentWindow = window;
3754
361k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3755
361k
    if (window)
3756
271k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3757
361k
}
3758
3759
void ImGui::GcCompactTransientMiscBuffers()
3760
0
{
3761
0
    ImGuiContext& g = *GImGui;
3762
0
    g.ItemFlagsStack.clear();
3763
0
    g.GroupStack.clear();
3764
0
    TableGcCompactSettings();
3765
0
}
3766
3767
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3768
// Not freed:
3769
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3770
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3771
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3772
1
{
3773
1
    window->MemoryCompacted = true;
3774
1
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3775
1
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3776
1
    window->IDStack.clear();
3777
1
    window->DrawList->_ClearFreeMemory();
3778
1
    window->DC.ChildWindows.clear();
3779
1
    window->DC.ItemWidthStack.clear();
3780
1
    window->DC.TextWrapPosStack.clear();
3781
1
}
3782
3783
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3784
0
{
3785
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3786
    // The other buffers tends to amortize much faster.
3787
0
    window->MemoryCompacted = false;
3788
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3789
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3790
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3791
0
}
3792
3793
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3794
62
{
3795
62
    ImGuiContext& g = *GImGui;
3796
3797
    // While most behaved code would make an effort to not steal active id during window move/drag operations,
3798
    // we at least need to be resilient to it. Cancelling the move is rather aggressive and users of 'master' branch
3799
    // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3800
62
    if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3801
0
    {
3802
0
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3803
0
        g.MovingWindow = NULL;
3804
0
    }
3805
3806
    // Set active id
3807
62
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3808
62
    if (g.ActiveIdIsJustActivated)
3809
62
    {
3810
62
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3811
62
        g.ActiveIdTimer = 0.0f;
3812
62
        g.ActiveIdHasBeenPressedBefore = false;
3813
62
        g.ActiveIdHasBeenEditedBefore = false;
3814
62
        g.ActiveIdMouseButton = -1;
3815
62
        if (id != 0)
3816
34
        {
3817
34
            g.LastActiveId = id;
3818
34
            g.LastActiveIdTimer = 0.0f;
3819
34
        }
3820
62
    }
3821
62
    g.ActiveId = id;
3822
62
    g.ActiveIdAllowOverlap = false;
3823
62
    g.ActiveIdNoClearOnFocusLoss = false;
3824
62
    g.ActiveIdWindow = window;
3825
62
    g.ActiveIdHasBeenEditedThisFrame = false;
3826
62
    if (id)
3827
34
    {
3828
34
        g.ActiveIdIsAlive = id;
3829
34
        g.ActiveIdSource = (g.NavActivateId == id || g.NavActivateInputId == id || g.NavJustMovedToId == id) ? (ImGuiInputSource)ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
3830
34
    }
3831
3832
    // Clear declaration of inputs claimed by the widget
3833
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3834
62
    g.ActiveIdUsingNavDirMask = 0x00;
3835
62
    g.ActiveIdUsingAllKeyboardKeys = false;
3836
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3837
    g.ActiveIdUsingNavInputMask = 0x00;
3838
#endif
3839
62
}
3840
3841
void ImGui::ClearActiveID()
3842
28
{
3843
28
    SetActiveID(0, NULL); // g.ActiveId = 0;
3844
28
}
3845
3846
void ImGui::SetHoveredID(ImGuiID id)
3847
334
{
3848
334
    ImGuiContext& g = *GImGui;
3849
334
    g.HoveredId = id;
3850
334
    g.HoveredIdAllowOverlap = false;
3851
334
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3852
41
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3853
334
}
3854
3855
ImGuiID ImGui::GetHoveredID()
3856
0
{
3857
0
    ImGuiContext& g = *GImGui;
3858
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3859
0
}
3860
3861
// This is called by ItemAdd().
3862
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
3863
void ImGui::KeepAliveID(ImGuiID id)
3864
181k
{
3865
181k
    ImGuiContext& g = *GImGui;
3866
181k
    if (g.ActiveId == id)
3867
191
        g.ActiveIdIsAlive = id;
3868
181k
    if (g.ActiveIdPreviousFrame == id)
3869
185
        g.ActiveIdPreviousFrameIsAlive = true;
3870
181k
}
3871
3872
void ImGui::MarkItemEdited(ImGuiID id)
3873
0
{
3874
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
3875
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
3876
0
    ImGuiContext& g = *GImGui;
3877
0
    IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
3878
0
    IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
3879
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
3880
0
    g.ActiveIdHasBeenEditedThisFrame = true;
3881
0
    g.ActiveIdHasBeenEditedBefore = true;
3882
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
3883
0
}
3884
3885
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
3886
334
{
3887
    // An active popup disable hovering on other windows (apart from its own children)
3888
    // FIXME-OPT: This could be cached/stored within the window.
3889
334
    ImGuiContext& g = *GImGui;
3890
334
    if (g.NavWindow)
3891
103
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
3892
103
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
3893
0
            {
3894
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
3895
                // NB: The 'else' is important because Modal windows are also Popups.
3896
0
                bool want_inhibit = false;
3897
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
3898
0
                    want_inhibit = true;
3899
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
3900
0
                    want_inhibit = true;
3901
3902
                // Inhibit hover unless the window is within the stack of our modal/popup
3903
0
                if (want_inhibit)
3904
0
                    if (!ImGui::IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
3905
0
                        return false;
3906
0
            }
3907
3908
    // Filter by viewport
3909
334
    if (window->Viewport != g.MouseViewport)
3910
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
3911
0
            return false;
3912
3913
334
    return true;
3914
334
}
3915
3916
// This is roughly matching the behavior of internal-facing ItemHoverable()
3917
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
3918
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
3919
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
3920
0
{
3921
0
    ImGuiContext& g = *GImGui;
3922
0
    ImGuiWindow* window = g.CurrentWindow;
3923
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
3924
0
    {
3925
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3926
0
            return false;
3927
0
        if (!IsItemFocused())
3928
0
            return false;
3929
0
    }
3930
0
    else
3931
0
    {
3932
        // Test for bounding box overlap, as updated as ItemAdd()
3933
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
3934
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
3935
0
            return false;
3936
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
3937
3938
        // Done with rectangle culling so we can perform heavier checks now
3939
        // Test if we are hovering the right window (our window could be behind another window)
3940
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
3941
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
3942
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
3943
        // the test that has been running for a long while.
3944
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
3945
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
3946
0
                return false;
3947
3948
        // Test if another item is active (e.g. being dragged)
3949
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
3950
0
            if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap)
3951
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
3952
0
                    return false;
3953
3954
        // Test if interactions on this window are blocked by an active popup or modal.
3955
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
3956
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
3957
0
            return false;
3958
3959
        // Test if the item is disabled
3960
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3961
0
            return false;
3962
3963
        // Special handling for calling after Begin() which represent the title bar or tab.
3964
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
3965
        // will never be overwritten so we need to detect the case.
3966
0
        if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)
3967
0
            return false;
3968
0
    }
3969
3970
    // Handle hover delay
3971
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
3972
0
    float delay;
3973
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
3974
0
        delay = g.IO.HoverDelayNormal;
3975
0
    else if (flags & ImGuiHoveredFlags_DelayShort)
3976
0
        delay = g.IO.HoverDelayShort;
3977
0
    else
3978
0
        delay = 0.0f;
3979
0
    if (delay > 0.0f)
3980
0
    {
3981
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
3982
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverDelayIdPreviousFrame != hover_delay_id))
3983
0
            g.HoverDelayTimer = 0.0f;
3984
0
        g.HoverDelayId = hover_delay_id;
3985
0
        return g.HoverDelayTimer >= delay;
3986
0
    }
3987
3988
0
    return true;
3989
0
}
3990
3991
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
3992
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
3993
181k
{
3994
181k
    ImGuiContext& g = *GImGui;
3995
181k
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
3996
26
        return false;
3997
3998
181k
    ImGuiWindow* window = g.CurrentWindow;
3999
181k
    if (g.HoveredWindow != window)
4000
180k
        return false;
4001
446
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4002
78
        return false;
4003
368
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4004
34
        return false;
4005
4006
    // Done with rectangle culling so we can perform heavier checks now.
4007
334
    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
4008
334
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4009
0
    {
4010
0
        g.HoveredIdDisabled = true;
4011
0
        return false;
4012
0
    }
4013
4014
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4015
    // hover test in widgets code. We could also decide to split this function is two.
4016
334
    if (id != 0)
4017
334
        SetHoveredID(id);
4018
4019
    // When disabled we'll return false but still set HoveredId
4020
334
    if (item_flags & ImGuiItemFlags_Disabled)
4021
0
    {
4022
        // Release active id if turning disabled
4023
0
        if (g.ActiveId == id)
4024
0
            ClearActiveID();
4025
0
        g.HoveredIdDisabled = true;
4026
0
        return false;
4027
0
    }
4028
4029
334
    if (id != 0)
4030
334
    {
4031
        // [DEBUG] Item Picker tool!
4032
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4033
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4034
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4035
334
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4036
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4037
334
        if (g.DebugItemPickerBreakId == id)
4038
0
            IM_DEBUG_BREAK();
4039
334
    }
4040
4041
334
    if (g.NavDisableMouseHover)
4042
0
        return false;
4043
4044
334
    return true;
4045
334
}
4046
4047
// FIXME: This is inlined/duplicated in ItemAdd()
4048
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4049
0
{
4050
0
    ImGuiContext& g = *GImGui;
4051
0
    ImGuiWindow* window = g.CurrentWindow;
4052
0
    if (!bb.Overlaps(window->ClipRect))
4053
0
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4054
0
            if (!g.LogEnabled)
4055
0
                return true;
4056
0
    return false;
4057
0
}
4058
4059
// This is also inlined in ItemAdd()
4060
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!
4061
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4062
180k
{
4063
180k
    ImGuiContext& g = *GImGui;
4064
180k
    g.LastItemData.ID = item_id;
4065
180k
    g.LastItemData.InFlags = in_flags;
4066
180k
    g.LastItemData.StatusFlags = item_flags;
4067
180k
    g.LastItemData.Rect = item_rect;
4068
180k
}
4069
4070
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4071
0
{
4072
0
    if (wrap_pos_x < 0.0f)
4073
0
        return 0.0f;
4074
4075
0
    ImGuiContext& g = *GImGui;
4076
0
    ImGuiWindow* window = g.CurrentWindow;
4077
0
    if (wrap_pos_x == 0.0f)
4078
0
    {
4079
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4080
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4081
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4082
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4083
        //else
4084
0
        wrap_pos_x = window->WorkRect.Max.x;
4085
0
    }
4086
0
    else if (wrap_pos_x > 0.0f)
4087
0
    {
4088
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4089
0
    }
4090
4091
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4092
0
}
4093
4094
// IM_ALLOC() == ImGui::MemAlloc()
4095
void* ImGui::MemAlloc(size_t size)
4096
1.20k
{
4097
1.20k
    if (ImGuiContext* ctx = GImGui)
4098
1.20k
        ctx->IO.MetricsActiveAllocations++;
4099
1.20k
    return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4100
1.20k
}
4101
4102
// IM_FREE() == ImGui::MemFree()
4103
void ImGui::MemFree(void* ptr)
4104
1.16k
{
4105
1.16k
    if (ptr)
4106
1.15k
        if (ImGuiContext* ctx = GImGui)
4107
1.15k
            ctx->IO.MetricsActiveAllocations--;
4108
1.16k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4109
1.16k
}
4110
4111
const char* ImGui::GetClipboardText()
4112
0
{
4113
0
    ImGuiContext& g = *GImGui;
4114
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4115
0
}
4116
4117
void ImGui::SetClipboardText(const char* text)
4118
0
{
4119
0
    ImGuiContext& g = *GImGui;
4120
0
    if (g.IO.SetClipboardTextFn)
4121
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4122
0
}
4123
4124
const char* ImGui::GetVersion()
4125
0
{
4126
0
    return IMGUI_VERSION;
4127
0
}
4128
4129
ImGuiIO& ImGui::GetIO()
4130
272k
{
4131
272k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4132
272k
    return GImGui->IO;
4133
272k
}
4134
4135
ImGuiPlatformIO& ImGui::GetPlatformIO()
4136
0
{
4137
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4138
0
    return GImGui->PlatformIO;
4139
0
}
4140
4141
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4142
ImDrawData* ImGui::GetDrawData()
4143
90.2k
{
4144
90.2k
    ImGuiContext& g = *GImGui;
4145
90.2k
    ImGuiViewportP* viewport = g.Viewports[0];
4146
90.2k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4147
90.2k
}
4148
4149
double ImGui::GetTime()
4150
0
{
4151
0
    return GImGui->Time;
4152
0
}
4153
4154
int ImGui::GetFrameCount()
4155
0
{
4156
0
    return GImGui->FrameCount;
4157
0
}
4158
4159
static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4160
0
{
4161
    // Create the draw list on demand, because they are not frequently used for all viewports
4162
0
    ImGuiContext& g = *GImGui;
4163
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
4164
0
    ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
4165
0
    if (draw_list == NULL)
4166
0
    {
4167
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4168
0
        draw_list->_OwnerName = drawlist_name;
4169
0
        viewport->DrawLists[drawlist_no] = draw_list;
4170
0
    }
4171
4172
    // Our ImDrawList system requires that there is always a command
4173
0
    if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
4174
0
    {
4175
0
        draw_list->_ResetForNewFrame();
4176
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4177
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4178
0
        viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
4179
0
    }
4180
0
    return draw_list;
4181
0
}
4182
4183
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4184
0
{
4185
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4186
0
}
4187
4188
ImDrawList* ImGui::GetBackgroundDrawList()
4189
0
{
4190
0
    ImGuiContext& g = *GImGui;
4191
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4192
0
}
4193
4194
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4195
0
{
4196
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4197
0
}
4198
4199
ImDrawList* ImGui::GetForegroundDrawList()
4200
0
{
4201
0
    ImGuiContext& g = *GImGui;
4202
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4203
0
}
4204
4205
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4206
0
{
4207
0
    return &GImGui->DrawListSharedData;
4208
0
}
4209
4210
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4211
7
{
4212
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4213
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4214
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4215
7
    ImGuiContext& g = *GImGui;
4216
7
    FocusWindow(window);
4217
7
    SetActiveID(window->MoveId, window);
4218
7
    g.NavDisableHighlight = true;
4219
7
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4220
7
    g.ActiveIdNoClearOnFocusLoss = true;
4221
7
    SetActiveIdUsingAllKeyboardKeys();
4222
4223
7
    bool can_move_window = true;
4224
7
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4225
0
        can_move_window = false;
4226
7
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4227
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4228
0
            can_move_window = false;
4229
7
    if (can_move_window)
4230
7
        g.MovingWindow = window;
4231
7
}
4232
4233
// We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4234
// - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
4235
// - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
4236
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
4237
6
{
4238
6
    ImGuiContext& g = *GImGui;
4239
6
    bool can_undock_node = false;
4240
6
    if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
4241
0
    {
4242
        // Can undock if:
4243
        // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
4244
        // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
4245
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4246
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4247
0
            if (undock_floating_node || root_node->IsDockSpace())
4248
0
                can_undock_node = true;
4249
0
    }
4250
4251
6
    const bool clicked = IsMouseClicked(0);
4252
6
    const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
4253
6
    if (can_undock_node && dragging)
4254
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4255
6
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4256
6
        StartMouseMovingWindow(window);
4257
6
}
4258
4259
// Handle mouse moving window
4260
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4261
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4262
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4263
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4264
void ImGui::UpdateMouseMovingWindowNewFrame()
4265
90.2k
{
4266
90.2k
    ImGuiContext& g = *GImGui;
4267
90.2k
    if (g.MovingWindow != NULL)
4268
60
    {
4269
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4270
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4271
60
        KeepAliveID(g.ActiveId);
4272
60
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4273
60
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4274
4275
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4276
60
        const bool window_disappared = ((!moving_window->WasActive && !moving_window->Active) || moving_window->Viewport == NULL);
4277
60
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4278
53
        {
4279
53
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4280
53
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4281
22
            {
4282
22
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4283
22
                if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4284
0
                {
4285
0
                    moving_window->Viewport->Pos = pos;
4286
0
                    moving_window->Viewport->UpdateWorkRect();
4287
0
                }
4288
22
            }
4289
53
            FocusWindow(g.MovingWindow);
4290
53
        }
4291
7
        else
4292
7
        {
4293
7
            if (!window_disappared)
4294
7
            {
4295
                // Try to merge the window back into the main viewport.
4296
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4297
7
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4298
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4299
4300
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4301
7
                if (!IsDragDropPayloadBeingAccepted())
4302
7
                    g.MouseViewport = moving_window->Viewport;
4303
4304
                // Clear the NoInput window flag set by the Viewport system
4305
7
                moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL.
4306
7
            }
4307
4308
7
            g.MovingWindow = NULL;
4309
7
            ClearActiveID();
4310
7
        }
4311
60
    }
4312
90.1k
    else
4313
90.1k
    {
4314
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4315
90.1k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4316
0
        {
4317
0
            KeepAliveID(g.ActiveId);
4318
0
            if (!g.IO.MouseDown[0])
4319
0
                ClearActiveID();
4320
0
        }
4321
90.1k
    }
4322
90.2k
}
4323
4324
// Initiate moving window when clicking on empty space or title bar.
4325
// Handle left-click and right-click focus.
4326
void ImGui::UpdateMouseMovingWindowEndFrame()
4327
90.2k
{
4328
90.2k
    ImGuiContext& g = *GImGui;
4329
90.2k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4330
392
        return;
4331
4332
    // Unless we just made a window/popup appear
4333
89.8k
    if (g.NavWindow && g.NavWindow->Appearing)
4334
1
        return;
4335
4336
    // Click on empty space to focus window and start moving
4337
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4338
89.8k
    if (g.IO.MouseClicked[0])
4339
3.72k
    {
4340
        // Handle the edge case of a popup being closed while clicking in its empty space.
4341
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4342
3.72k
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4343
3.72k
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4344
4345
3.72k
        if (root_window != NULL && !is_closed_popup)
4346
1
        {
4347
1
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4348
4349
            // Cancel moving if clicked outside of title bar
4350
1
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4351
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4352
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4353
0
                        g.MovingWindow = NULL;
4354
4355
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4356
1
            if (g.HoveredIdDisabled)
4357
0
                g.MovingWindow = NULL;
4358
1
        }
4359
3.72k
        else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
4360
2
        {
4361
            // Clicking on void disable focus
4362
2
            FocusWindow(NULL);
4363
2
        }
4364
3.72k
    }
4365
4366
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4367
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4368
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4369
89.8k
    if (g.IO.MouseClicked[1])
4370
511
    {
4371
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4372
        // This is where we can trim the popup stack.
4373
511
        ImGuiWindow* modal = GetTopMostPopupModal();
4374
511
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4375
511
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4376
511
    }
4377
89.8k
}
4378
4379
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4380
// Need to keep in sync with SetWindowPos()
4381
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4382
0
{
4383
0
    window->Pos += delta;
4384
0
    window->ClipRect.Translate(delta);
4385
0
    window->OuterRectClipped.Translate(delta);
4386
0
    window->InnerRect.Translate(delta);
4387
0
    window->DC.CursorPos += delta;
4388
0
    window->DC.CursorStartPos += delta;
4389
0
    window->DC.CursorMaxPos += delta;
4390
0
    window->DC.IdealMaxPos += delta;
4391
0
}
4392
4393
static void ScaleWindow(ImGuiWindow* window, float scale)
4394
0
{
4395
0
    ImVec2 origin = window->Viewport->Pos;
4396
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4397
0
    window->Size = ImFloor(window->Size * scale);
4398
0
    window->SizeFull = ImFloor(window->SizeFull * scale);
4399
0
    window->ContentSize = ImFloor(window->ContentSize * scale);
4400
0
}
4401
4402
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4403
270k
{
4404
270k
    return (window->Active) && (!window->Hidden);
4405
270k
}
4406
4407
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4408
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4409
90.2k
{
4410
90.2k
    ImGuiContext& g = *GImGui;
4411
90.2k
    ImGuiIO& io = g.IO;
4412
90.2k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4413
4414
    // Find the window hovered by mouse:
4415
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4416
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4417
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4418
90.2k
    bool clear_hovered_windows = false;
4419
90.2k
    FindHoveredWindow();
4420
90.2k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4421
4422
    // Modal windows prevents mouse from hovering behind them.
4423
90.2k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4424
90.2k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4425
0
        clear_hovered_windows = true;
4426
4427
    // Disabled mouse?
4428
90.2k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4429
0
        clear_hovered_windows = true;
4430
4431
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4432
    // won't report hovering nor request capture even while dragging over our windows afterward.
4433
90.2k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4434
90.2k
    const bool has_open_modal = (modal_window != NULL);
4435
90.2k
    int mouse_earliest_down = -1;
4436
90.2k
    bool mouse_any_down = false;
4437
541k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4438
451k
    {
4439
451k
        if (io.MouseClicked[i])
4440
6.99k
        {
4441
6.99k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4442
6.99k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4443
6.99k
        }
4444
451k
        mouse_any_down |= io.MouseDown[i];
4445
451k
        if (io.MouseDown[i])
4446
48.1k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4447
32.3k
                mouse_earliest_down = i;
4448
451k
    }
4449
90.2k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4450
90.2k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4451
4452
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4453
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4454
90.2k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4455
90.2k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4456
28.8k
        clear_hovered_windows = true;
4457
4458
90.2k
    if (clear_hovered_windows)
4459
28.8k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4460
4461
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4462
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4463
90.2k
    if (g.WantCaptureMouseNextFrame != -1)
4464
0
    {
4465
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4466
0
    }
4467
90.2k
    else
4468
90.2k
    {
4469
90.2k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4470
90.2k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4471
90.2k
    }
4472
4473
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4474
90.2k
    if (g.WantCaptureKeyboardNextFrame != -1)
4475
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4476
90.2k
    else
4477
90.2k
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4478
90.2k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4479
345
        io.WantCaptureKeyboard = true;
4480
4481
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4482
90.2k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4483
90.2k
}
4484
4485
void ImGui::NewFrame()
4486
90.2k
{
4487
90.2k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4488
90.2k
    ImGuiContext& g = *GImGui;
4489
4490
    // Remove pending delete hooks before frame start.
4491
    // This deferred removal avoid issues of removal while iterating the hook vector
4492
90.2k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4493
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4494
0
            g.Hooks.erase(&g.Hooks[n]);
4495
4496
90.2k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4497
4498
    // Check and assert for various common IO and Configuration mistakes
4499
90.2k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4500
90.2k
    ErrorCheckNewFrameSanityChecks();
4501
90.2k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4502
4503
    // Load settings on first frame, save settings when modified (after a delay)
4504
90.2k
    UpdateSettings();
4505
4506
90.2k
    g.Time += g.IO.DeltaTime;
4507
90.2k
    g.WithinFrameScope = true;
4508
90.2k
    g.FrameCount += 1;
4509
90.2k
    g.TooltipOverrideCount = 0;
4510
90.2k
    g.WindowsActiveCount = 0;
4511
90.2k
    g.MenusIdSubmittedThisFrame.resize(0);
4512
4513
    // Calculate frame-rate for the user, as a purely luxurious feature
4514
90.2k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4515
90.2k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4516
90.2k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4517
90.2k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4518
90.2k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4519
4520
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4521
90.2k
    g.InputEventsTrail.resize(0);
4522
90.2k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4523
4524
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4525
90.2k
    UpdateViewportsNewFrame();
4526
4527
    // Setup current font and draw list shared data
4528
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4529
90.2k
    g.IO.Fonts->Locked = true;
4530
90.2k
    SetCurrentFont(GetDefaultFont());
4531
90.2k
    IM_ASSERT(g.Font->IsLoaded());
4532
90.2k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4533
180k
    for (int n = 0; n < g.Viewports.Size; n++)
4534
90.2k
        virtual_space.Add(g.Viewports[n]->GetMainRect());
4535
90.2k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4536
90.2k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4537
90.2k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4538
90.2k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4539
90.2k
    if (g.Style.AntiAliasedLines)
4540
90.2k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4541
90.2k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4542
90.2k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4543
90.2k
    if (g.Style.AntiAliasedFill)
4544
90.2k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4545
90.2k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4546
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4547
4548
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4549
180k
    for (int n = 0; n < g.Viewports.Size; n++)
4550
90.2k
    {
4551
90.2k
        ImGuiViewportP* viewport = g.Viewports[n];
4552
90.2k
        viewport->DrawData = NULL;
4553
90.2k
        viewport->DrawDataP.Clear();
4554
90.2k
    }
4555
4556
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4557
90.2k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4558
44
        KeepAliveID(g.DragDropPayload.SourceId);
4559
4560
    // Update HoveredId data
4561
90.2k
    if (!g.HoveredIdPreviousFrame)
4562
89.8k
        g.HoveredIdTimer = 0.0f;
4563
90.2k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4564
89.9k
        g.HoveredIdNotActiveTimer = 0.0f;
4565
90.2k
    if (g.HoveredId)
4566
334
        g.HoveredIdTimer += g.IO.DeltaTime;
4567
90.2k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4568
247
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4569
90.2k
    g.HoveredIdPreviousFrame = g.HoveredId;
4570
90.2k
    g.HoveredId = 0;
4571
90.2k
    g.HoveredIdAllowOverlap = false;
4572
90.2k
    g.HoveredIdDisabled = false;
4573
4574
    // Clear ActiveID if the item is not alive anymore.
4575
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4576
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4577
90.2k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4578
0
    {
4579
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4580
0
        ClearActiveID();
4581
0
    }
4582
4583
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4584
90.2k
    if (g.ActiveId)
4585
147
        g.ActiveIdTimer += g.IO.DeltaTime;
4586
90.2k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4587
90.2k
    g.ActiveIdPreviousFrame = g.ActiveId;
4588
90.2k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4589
90.2k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4590
90.2k
    g.ActiveIdIsAlive = 0;
4591
90.2k
    g.ActiveIdHasBeenEditedThisFrame = false;
4592
90.2k
    g.ActiveIdPreviousFrameIsAlive = false;
4593
90.2k
    g.ActiveIdIsJustActivated = false;
4594
90.2k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4595
0
        g.TempInputId = 0;
4596
90.2k
    if (g.ActiveId == 0)
4597
90.0k
    {
4598
90.0k
        g.ActiveIdUsingNavDirMask = 0x00;
4599
90.0k
        g.ActiveIdUsingAllKeyboardKeys = false;
4600
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4601
        g.ActiveIdUsingNavInputMask = 0x00;
4602
#endif
4603
90.0k
    }
4604
4605
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4606
    if (g.ActiveId == 0)
4607
        g.ActiveIdUsingNavInputMask = 0;
4608
    else if (g.ActiveIdUsingNavInputMask != 0)
4609
    {
4610
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4611
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4612
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4613
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4614
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4615
            IM_ASSERT(0); // Other values unsupported
4616
    }
4617
#endif
4618
4619
    // Update hover delay for IsItemHovered() with delays and tooltips
4620
90.2k
    g.HoverDelayIdPreviousFrame = g.HoverDelayId;
4621
90.2k
    if (g.HoverDelayId != 0)
4622
0
    {
4623
        //if (g.IO.MouseDelta.x == 0.0f && g.IO.MouseDelta.y == 0.0f) // Need design/flags
4624
0
        g.HoverDelayTimer += g.IO.DeltaTime;
4625
0
        g.HoverDelayClearTimer = 0.0f;
4626
0
        g.HoverDelayId = 0;
4627
0
    }
4628
90.2k
    else if (g.HoverDelayTimer > 0.0f)
4629
0
    {
4630
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4631
0
        g.HoverDelayClearTimer += g.IO.DeltaTime;
4632
0
        if (g.HoverDelayClearTimer >= ImMax(0.20f, g.IO.DeltaTime * 2.0f)) // ~6 frames at 30 Hz + allow for low framerate
4633
0
            g.HoverDelayTimer = g.HoverDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4634
0
    }
4635
4636
    // Drag and drop
4637
90.2k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4638
90.2k
    g.DragDropAcceptIdCurr = 0;
4639
90.2k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4640
90.2k
    g.DragDropWithinSource = false;
4641
90.2k
    g.DragDropWithinTarget = false;
4642
90.2k
    g.DragDropHoldJustPressedId = 0;
4643
4644
    // Close popups on focus lost (currently wip/opt-in)
4645
    //if (g.IO.AppFocusLost)
4646
    //    ClosePopupsExceptModals();
4647
4648
    // Update keyboard input state
4649
90.2k
    UpdateKeyboardInputs();
4650
4651
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4652
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4653
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4654
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4655
4656
    // Update gamepad/keyboard navigation
4657
90.2k
    NavUpdate();
4658
4659
    // Update mouse input state
4660
90.2k
    UpdateMouseInputs();
4661
4662
    // Undocking
4663
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4664
90.2k
    DockContextNewFrameUpdateUndocking(&g);
4665
4666
    // Find hovered window
4667
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4668
90.2k
    UpdateHoveredWindowAndCaptureFlags();
4669
4670
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4671
90.2k
    UpdateMouseMovingWindowNewFrame();
4672
4673
    // Background darkening/whitening
4674
90.2k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4675
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4676
90.2k
    else
4677
90.2k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4678
4679
90.2k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4680
90.2k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4681
4682
    // Platform IME data: reset for the frame
4683
90.2k
    g.PlatformImeDataPrev = g.PlatformImeData;
4684
90.2k
    g.PlatformImeData.WantVisible = false;
4685
4686
    // Mouse wheel scrolling, scale
4687
90.2k
    UpdateMouseWheel();
4688
4689
    // Mark all windows as not visible and compact unused memory.
4690
90.2k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4691
90.2k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4692
360k
    for (int i = 0; i != g.Windows.Size; i++)
4693
270k
    {
4694
270k
        ImGuiWindow* window = g.Windows[i];
4695
270k
        window->WasActive = window->Active;
4696
270k
        window->Active = false;
4697
270k
        window->WriteAccessed = false;
4698
270k
        window->BeginCountPreviousFrame = window->BeginCount;
4699
270k
        window->BeginCount = 0;
4700
4701
        // Garbage collect transient buffers of recently unused windows
4702
270k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4703
1
            GcCompactTransientWindowBuffers(window);
4704
270k
    }
4705
4706
    // Garbage collect transient buffers of recently unused tables
4707
90.2k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4708
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4709
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4710
90.2k
    for (int i = 0; i < g.TablesTempData.Size; i++)
4711
0
        if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)
4712
0
            TableGcCompactTransientBuffers(&g.TablesTempData[i]);
4713
90.2k
    if (g.GcCompactAll)
4714
0
        GcCompactTransientMiscBuffers();
4715
90.2k
    g.GcCompactAll = false;
4716
4717
    // Closing the focused window restore focus to the first active root window in descending z-order
4718
90.2k
    if (g.NavWindow && !g.NavWindow->WasActive)
4719
0
        FocusTopMostWindowUnderOne(NULL, NULL);
4720
4721
    // No window should be open at the beginning of the frame.
4722
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4723
90.2k
    g.CurrentWindowStack.resize(0);
4724
90.2k
    g.BeginPopupStack.resize(0);
4725
90.2k
    g.ItemFlagsStack.resize(0);
4726
90.2k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4727
90.2k
    g.GroupStack.resize(0);
4728
4729
    // Docking
4730
90.2k
    DockContextNewFrameUpdateDocking(&g);
4731
4732
    // [DEBUG] Update debug features
4733
90.2k
    UpdateDebugToolItemPicker();
4734
90.2k
    UpdateDebugToolStackQueries();
4735
90.2k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4736
0
        g.DebugLocateId = 0;
4737
4738
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4739
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4740
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4741
90.2k
    g.WithinFrameScopeWithImplicitWindow = true;
4742
90.2k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4743
90.2k
    Begin("Debug##Default");
4744
90.2k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4745
4746
90.2k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
4747
90.2k
}
4748
4749
// FIXME: Add a more explicit sort order in the window structure.
4750
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
4751
0
{
4752
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
4753
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
4754
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
4755
0
        return d;
4756
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
4757
0
        return d;
4758
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
4759
0
}
4760
4761
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
4762
270k
{
4763
270k
    out_sorted_windows->push_back(window);
4764
270k
    if (window->Active)
4765
90.5k
    {
4766
90.5k
        int count = window->DC.ChildWindows.Size;
4767
90.5k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
4768
90.8k
        for (int i = 0; i < count; i++)
4769
311
        {
4770
311
            ImGuiWindow* child = window->DC.ChildWindows[i];
4771
311
            if (child->Active)
4772
311
                AddWindowToSortBuffer(out_sorted_windows, child);
4773
311
        }
4774
90.5k
    }
4775
270k
}
4776
4777
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
4778
90.5k
{
4779
90.5k
    if (draw_list->CmdBuffer.Size == 0)
4780
0
        return;
4781
90.5k
    if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)
4782
14
        return;
4783
4784
    // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
4785
    // May trigger for you if you are using PrimXXX functions incorrectly.
4786
90.5k
    IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
4787
90.5k
    IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
4788
90.5k
    if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
4789
90.5k
        IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
4790
4791
    // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
4792
    // If this assert triggers because you are drawing lots of stuff manually:
4793
    // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
4794
    //   Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
4795
    // - If you want large meshes with more than 64K vertices, you can either:
4796
    //   (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
4797
    //       Most example backends already support this from 1.71. Pre-1.71 backends won't.
4798
    //       Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
4799
    //   (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
4800
    //       Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
4801
    //         glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
4802
    //       Your own engine or render API may use different parameters or function calls to specify index sizes.
4803
    //       2 and 4 bytes indices are generally supported by most graphics API.
4804
    // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
4805
    //   the 64K limit to split your draw commands in multiple draw lists.
4806
90.5k
    if (sizeof(ImDrawIdx) == 2)
4807
90.5k
        IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
4808
4809
90.5k
    out_list->push_back(draw_list);
4810
90.5k
}
4811
4812
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
4813
90.5k
{
4814
90.5k
    ImGuiContext& g = *GImGui;
4815
90.5k
    ImGuiViewportP* viewport = window->Viewport;
4816
90.5k
    g.IO.MetricsRenderWindows++;
4817
90.5k
    if (window->Flags & ImGuiWindowFlags_DockNodeHost)
4818
0
        window->DrawList->ChannelsMerge();
4819
90.5k
    AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
4820
90.8k
    for (int i = 0; i < window->DC.ChildWindows.Size; i++)
4821
310
    {
4822
310
        ImGuiWindow* child = window->DC.ChildWindows[i];
4823
310
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
4824
310
            AddWindowToDrawData(child, layer);
4825
310
    }
4826
90.5k
}
4827
4828
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
4829
90.2k
{
4830
90.2k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
4831
90.2k
}
4832
4833
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
4834
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
4835
90.2k
{
4836
90.2k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
4837
90.2k
}
4838
4839
void ImDrawDataBuilder::FlattenIntoSingleLayer()
4840
90.2k
{
4841
90.2k
    int n = Layers[0].Size;
4842
90.2k
    int size = n;
4843
180k
    for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
4844
90.2k
        size += Layers[i].Size;
4845
90.2k
    Layers[0].resize(size);
4846
180k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
4847
90.2k
    {
4848
90.2k
        ImVector<ImDrawList*>& layer = Layers[layer_n];
4849
90.2k
        if (layer.empty())
4850
90.2k
            continue;
4851
0
        memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
4852
0
        n += layer.Size;
4853
0
        layer.resize(0);
4854
0
    }
4855
90.2k
}
4856
4857
static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
4858
90.2k
{
4859
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
4860
    // and to allow applications/backends to easily skip rendering.
4861
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
4862
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
4863
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
4864
90.2k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_Minimized) != 0;
4865
4866
90.2k
    ImGuiIO& io = ImGui::GetIO();
4867
90.2k
    ImDrawData* draw_data = &viewport->DrawDataP;
4868
90.2k
    viewport->DrawData = draw_data; // Make publicly accessible
4869
90.2k
    draw_data->Valid = true;
4870
90.2k
    draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
4871
90.2k
    draw_data->CmdListsCount = draw_lists->Size;
4872
90.2k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
4873
90.2k
    draw_data->DisplayPos = viewport->Pos;
4874
90.2k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
4875
90.2k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
4876
90.2k
    draw_data->OwnerViewport = viewport;
4877
180k
    for (int n = 0; n < draw_lists->Size; n++)
4878
90.5k
    {
4879
90.5k
        ImDrawList* draw_list = draw_lists->Data[n];
4880
90.5k
        draw_list->_PopUnusedDrawCmd();
4881
90.5k
        draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;
4882
90.5k
        draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;
4883
90.5k
    }
4884
90.2k
}
4885
4886
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
4887
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
4888
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
4889
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
4890
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
4891
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
4892
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
4893
361k
{
4894
361k
    ImGuiWindow* window = GetCurrentWindow();
4895
361k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
4896
361k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
4897
361k
}
4898
4899
void ImGui::PopClipRect()
4900
180k
{
4901
180k
    ImGuiWindow* window = GetCurrentWindow();
4902
180k
    window->DrawList->PopClipRect();
4903
180k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
4904
180k
}
4905
4906
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
4907
0
{
4908
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
4909
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
4910
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
4911
0
    return window;
4912
0
}
4913
4914
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
4915
0
{
4916
0
    if ((col & IM_COL32_A_MASK) == 0)
4917
0
        return;
4918
4919
0
    ImGuiViewportP* viewport = window->Viewport;
4920
0
    ImRect viewport_rect = viewport->GetMainRect();
4921
4922
    // Draw behind window by moving the draw command at the FRONT of the draw list
4923
0
    {
4924
        // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
4925
        // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
4926
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
4927
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
4928
0
        if (draw_list->CmdBuffer.Size == 0)
4929
0
            draw_list->AddDrawCmd();
4930
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged
4931
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
4932
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
4933
0
        IM_ASSERT(cmd.ElemCount == 6);
4934
0
        draw_list->CmdBuffer.pop_back();
4935
0
        draw_list->CmdBuffer.push_front(cmd);
4936
0
        draw_list->PopClipRect();
4937
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
4938
0
    }
4939
4940
    // Draw over sibling docking nodes in a same docking tree
4941
0
    if (window->RootWindow->DockIsActive)
4942
0
    {
4943
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
4944
0
        if (draw_list->CmdBuffer.Size == 0)
4945
0
            draw_list->AddDrawCmd();
4946
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
4947
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
4948
0
        draw_list->PopClipRect();
4949
0
    }
4950
0
}
4951
4952
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
4953
0
{
4954
0
    ImGuiContext& g = *GImGui;
4955
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
4956
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
4957
0
    {
4958
0
        ImGuiWindow* window = g.Windows[i];
4959
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
4960
0
            continue;
4961
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
4962
0
            break;
4963
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
4964
0
            bottom_most_visible_window = window;
4965
0
    }
4966
0
    return bottom_most_visible_window;
4967
0
}
4968
4969
static void ImGui::RenderDimmedBackgrounds()
4970
90.2k
{
4971
90.2k
    ImGuiContext& g = *GImGui;
4972
90.2k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
4973
90.2k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
4974
90.2k
        return;
4975
0
    const bool dim_bg_for_modal = (modal_window != NULL);
4976
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
4977
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
4978
0
        return;
4979
4980
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
4981
0
    if (dim_bg_for_modal)
4982
0
    {
4983
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
4984
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
4985
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
4986
0
        viewports_already_dimmed[0] = modal_window->Viewport;
4987
0
    }
4988
0
    else if (dim_bg_for_window_list)
4989
0
    {
4990
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
4991
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
4992
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
4993
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
4994
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
4995
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
4996
4997
        // Draw border around CTRL+Tab target window
4998
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
4999
0
        ImGuiViewport* viewport = window->Viewport;
5000
0
        float distance = g.FontSize;
5001
0
        ImRect bb = window->Rect();
5002
0
        bb.Expand(distance);
5003
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5004
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5005
0
        if (window->DrawList->CmdBuffer.Size == 0)
5006
0
            window->DrawList->AddDrawCmd();
5007
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5008
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5009
0
        window->DrawList->PopClipRect();
5010
0
    }
5011
5012
    // Draw dimming background on _other_ viewports than the ones our windows are in
5013
0
    for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
5014
0
    {
5015
0
        ImGuiViewportP* viewport = g.Viewports[viewport_n];
5016
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5017
0
            continue;
5018
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5019
0
            continue;
5020
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5021
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5022
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5023
0
    }
5024
0
}
5025
5026
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5027
void ImGui::EndFrame()
5028
180k
{
5029
180k
    ImGuiContext& g = *GImGui;
5030
180k
    IM_ASSERT(g.Initialized);
5031
5032
    // Don't process EndFrame() multiple times.
5033
180k
    if (g.FrameCountEnded == g.FrameCount)
5034
90.2k
        return;
5035
90.2k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5036
5037
90.2k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5038
5039
90.2k
    ErrorCheckEndFrameSanityChecks();
5040
5041
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5042
90.2k
    if (g.IO.SetPlatformImeDataFn && memcmp(&g.PlatformImeData, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5043
0
    {
5044
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5045
0
        g.IO.SetPlatformImeDataFn(viewport ? viewport : GetMainViewport(), &g.PlatformImeData);
5046
0
    }
5047
5048
    // Hide implicit/fallback "Debug" window if it hasn't been used
5049
90.2k
    g.WithinFrameScopeWithImplicitWindow = false;
5050
90.2k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5051
90.2k
        g.CurrentWindow->Active = false;
5052
90.2k
    End();
5053
5054
    // Update navigation: CTRL+Tab, wrap-around requests
5055
90.2k
    NavEndFrame();
5056
5057
    // Update docking
5058
90.2k
    DockContextEndFrame(&g);
5059
5060
90.2k
    SetCurrentViewport(NULL, NULL);
5061
5062
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5063
90.2k
    if (g.DragDropActive)
5064
55
    {
5065
55
        bool is_delivered = g.DragDropPayload.Delivery;
5066
55
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5067
55
        if (is_delivered || is_elapsed)
5068
6
            ClearDragDrop();
5069
55
    }
5070
5071
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5072
90.2k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5073
0
    {
5074
0
        g.DragDropWithinSource = true;
5075
0
        SetTooltip("...");
5076
0
        g.DragDropWithinSource = false;
5077
0
    }
5078
5079
    // End frame
5080
90.2k
    g.WithinFrameScope = false;
5081
90.2k
    g.FrameCountEnded = g.FrameCount;
5082
5083
    // Initiate moving window + handle left-click and right-click focus
5084
90.2k
    UpdateMouseMovingWindowEndFrame();
5085
5086
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5087
90.2k
    UpdateViewportsEndFrame();
5088
5089
    // Sort the window list so that all child windows are after their parent
5090
    // We cannot do that on FocusWindow() because children may not exist yet
5091
90.2k
    g.WindowsTempSortBuffer.resize(0);
5092
90.2k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5093
360k
    for (int i = 0; i != g.Windows.Size; i++)
5094
270k
    {
5095
270k
        ImGuiWindow* window = g.Windows[i];
5096
270k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5097
311
            continue;
5098
270k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5099
270k
    }
5100
5101
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5102
90.2k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5103
90.2k
    g.Windows.swap(g.WindowsTempSortBuffer);
5104
90.2k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5105
5106
    // Unlock font atlas
5107
90.2k
    g.IO.Fonts->Locked = false;
5108
5109
    // Clear Input data for next frame
5110
90.2k
    g.IO.AppFocusLost = false;
5111
90.2k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5112
90.2k
    g.IO.InputQueueCharacters.resize(0);
5113
5114
90.2k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5115
90.2k
}
5116
5117
// Prepare the data for rendering so you can call GetDrawData()
5118
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5119
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5120
void ImGui::Render()
5121
90.2k
{
5122
90.2k
    ImGuiContext& g = *GImGui;
5123
90.2k
    IM_ASSERT(g.Initialized);
5124
5125
90.2k
    if (g.FrameCountEnded != g.FrameCount)
5126
90.2k
        EndFrame();
5127
90.2k
    const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);
5128
90.2k
    g.FrameCountRendered = g.FrameCount;
5129
90.2k
    g.IO.MetricsRenderWindows = 0;
5130
5131
90.2k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5132
5133
    // Add background ImDrawList (for each active viewport)
5134
180k
    for (int n = 0; n != g.Viewports.Size; n++)
5135
90.2k
    {
5136
90.2k
        ImGuiViewportP* viewport = g.Viewports[n];
5137
90.2k
        viewport->DrawDataBuilder.Clear();
5138
90.2k
        if (viewport->DrawLists[0] != NULL)
5139
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5140
90.2k
    }
5141
5142
    // Add ImDrawList to render
5143
90.2k
    ImGuiWindow* windows_to_render_top_most[2];
5144
90.2k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5145
90.2k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5146
360k
    for (int n = 0; n != g.Windows.Size; n++)
5147
270k
    {
5148
270k
        ImGuiWindow* window = g.Windows[n];
5149
270k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5150
270k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5151
90.2k
            AddRootWindowToDrawData(window);
5152
270k
    }
5153
270k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5154
180k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5155
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5156
5157
    // Draw modal/window whitening backgrounds
5158
90.2k
    if (first_render_of_frame)
5159
90.2k
        RenderDimmedBackgrounds();
5160
5161
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5162
90.2k
    if (g.IO.MouseDrawCursor && first_render_of_frame && g.MouseCursor != ImGuiMouseCursor_None)
5163
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5164
5165
    // Setup ImDrawData structures for end-user
5166
90.2k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5167
180k
    for (int n = 0; n < g.Viewports.Size; n++)
5168
90.2k
    {
5169
90.2k
        ImGuiViewportP* viewport = g.Viewports[n];
5170
90.2k
        viewport->DrawDataBuilder.FlattenIntoSingleLayer();
5171
5172
        // Add foreground ImDrawList (for each active viewport)
5173
90.2k
        if (viewport->DrawLists[1] != NULL)
5174
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5175
5176
90.2k
        SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
5177
90.2k
        ImDrawData* draw_data = viewport->DrawData;
5178
90.2k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5179
90.2k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5180
90.2k
    }
5181
5182
90.2k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5183
90.2k
}
5184
5185
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5186
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5187
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5188
180k
{
5189
180k
    ImGuiContext& g = *GImGui;
5190
5191
180k
    const char* text_display_end;
5192
180k
    if (hide_text_after_double_hash)
5193
180k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5194
0
    else
5195
0
        text_display_end = text_end;
5196
5197
180k
    ImFont* font = g.Font;
5198
180k
    const float font_size = g.FontSize;
5199
180k
    if (text == text_display_end)
5200
0
        return ImVec2(0.0f, font_size);
5201
180k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5202
5203
    // Round
5204
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5205
    // FIXME: Investigate using ceilf or e.g.
5206
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5207
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5208
180k
    text_size.x = IM_FLOOR(text_size.x + 0.99999f);
5209
5210
180k
    return text_size;
5211
180k
}
5212
5213
// Find window given position, search front-to-back
5214
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5215
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5216
// called, aka before the next Begin(). Moving window isn't affected.
5217
static void FindHoveredWindow()
5218
90.2k
{
5219
90.2k
    ImGuiContext& g = *GImGui;
5220
5221
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5222
90.2k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5223
90.2k
    if (g.MovingWindow)
5224
60
        g.MovingWindow->Viewport = g.MouseViewport;
5225
5226
90.2k
    ImGuiWindow* hovered_window = NULL;
5227
90.2k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5228
90.2k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5229
60
        hovered_window = g.MovingWindow;
5230
5231
90.2k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5232
90.2k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5233
359k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5234
269k
    {
5235
269k
        ImGuiWindow* window = g.Windows[i];
5236
269k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5237
269k
        if (!window->Active || window->Hidden)
5238
179k
            continue;
5239
90.5k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5240
0
            continue;
5241
90.5k
        IM_ASSERT(window->Viewport);
5242
90.5k
        if (window->Viewport != g.MouseViewport)
5243
0
            continue;
5244
5245
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5246
90.5k
        ImRect bb(window->OuterRectClipped);
5247
90.5k
        if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
5248
310
            bb.Expand(padding_regular);
5249
90.2k
        else
5250
90.2k
            bb.Expand(padding_for_resize);
5251
90.5k
        if (!bb.Contains(g.IO.MousePos))
5252
89.7k
            continue;
5253
5254
        // Support for one rectangular hole in any given window
5255
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5256
814
        if (window->HitTestHoleSize.x != 0)
5257
0
        {
5258
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5259
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5260
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5261
0
                continue;
5262
0
        }
5263
5264
814
        if (hovered_window == NULL)
5265
777
            hovered_window = window;
5266
814
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5267
814
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5268
777
            hovered_window_ignoring_moving_window = window;
5269
814
        if (hovered_window && hovered_window_ignoring_moving_window)
5270
777
            break;
5271
814
    }
5272
5273
90.2k
    g.HoveredWindow = hovered_window;
5274
90.2k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5275
5276
90.2k
    if (g.MovingWindow)
5277
60
        g.MovingWindow->Viewport = moving_window_viewport;
5278
90.2k
}
5279
5280
bool ImGui::IsItemActive()
5281
180k
{
5282
180k
    ImGuiContext& g = *GImGui;
5283
180k
    if (g.ActiveId)
5284
300
        return g.ActiveId == g.LastItemData.ID;
5285
180k
    return false;
5286
180k
}
5287
5288
bool ImGui::IsItemActivated()
5289
0
{
5290
0
    ImGuiContext& g = *GImGui;
5291
0
    if (g.ActiveId)
5292
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5293
0
            return true;
5294
0
    return false;
5295
0
}
5296
5297
bool ImGui::IsItemDeactivated()
5298
0
{
5299
0
    ImGuiContext& g = *GImGui;
5300
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5301
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5302
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5303
0
}
5304
5305
bool ImGui::IsItemDeactivatedAfterEdit()
5306
0
{
5307
0
    ImGuiContext& g = *GImGui;
5308
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5309
0
}
5310
5311
// == GetItemID() == GetFocusID()
5312
bool ImGui::IsItemFocused()
5313
0
{
5314
0
    ImGuiContext& g = *GImGui;
5315
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5316
0
        return false;
5317
5318
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5319
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5320
0
    ImGuiWindow* window = g.CurrentWindow;
5321
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5322
0
        return false;
5323
5324
0
    return true;
5325
0
}
5326
5327
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5328
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5329
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5330
0
{
5331
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5332
0
}
5333
5334
bool ImGui::IsItemToggledOpen()
5335
0
{
5336
0
    ImGuiContext& g = *GImGui;
5337
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5338
0
}
5339
5340
bool ImGui::IsItemToggledSelection()
5341
0
{
5342
0
    ImGuiContext& g = *GImGui;
5343
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5344
0
}
5345
5346
bool ImGui::IsAnyItemHovered()
5347
0
{
5348
0
    ImGuiContext& g = *GImGui;
5349
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5350
0
}
5351
5352
bool ImGui::IsAnyItemActive()
5353
0
{
5354
0
    ImGuiContext& g = *GImGui;
5355
0
    return g.ActiveId != 0;
5356
0
}
5357
5358
bool ImGui::IsAnyItemFocused()
5359
0
{
5360
0
    ImGuiContext& g = *GImGui;
5361
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5362
0
}
5363
5364
bool ImGui::IsItemVisible()
5365
0
{
5366
0
    ImGuiContext& g = *GImGui;
5367
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5368
0
}
5369
5370
bool ImGui::IsItemEdited()
5371
0
{
5372
0
    ImGuiContext& g = *GImGui;
5373
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5374
0
}
5375
5376
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5377
// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
5378
void ImGui::SetItemAllowOverlap()
5379
0
{
5380
0
    ImGuiContext& g = *GImGui;
5381
0
    ImGuiID id = g.LastItemData.ID;
5382
0
    if (g.HoveredId == id)
5383
0
        g.HoveredIdAllowOverlap = true;
5384
0
    if (g.ActiveId == id)
5385
0
        g.ActiveIdAllowOverlap = true;
5386
0
}
5387
5388
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5389
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5390
50
{
5391
50
    ImGuiContext& g = *GImGui;
5392
50
    IM_ASSERT(g.ActiveId != 0);
5393
50
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5394
50
    g.ActiveIdUsingAllKeyboardKeys = true;
5395
50
    NavMoveRequestCancel();
5396
50
}
5397
5398
ImGuiID ImGui::GetItemID()
5399
0
{
5400
0
    ImGuiContext& g = *GImGui;
5401
0
    return g.LastItemData.ID;
5402
0
}
5403
5404
ImVec2 ImGui::GetItemRectMin()
5405
0
{
5406
0
    ImGuiContext& g = *GImGui;
5407
0
    return g.LastItemData.Rect.Min;
5408
0
}
5409
5410
ImVec2 ImGui::GetItemRectMax()
5411
0
{
5412
0
    ImGuiContext& g = *GImGui;
5413
0
    return g.LastItemData.Rect.Max;
5414
0
}
5415
5416
ImVec2 ImGui::GetItemRectSize()
5417
0
{
5418
0
    ImGuiContext& g = *GImGui;
5419
0
    return g.LastItemData.Rect.GetSize();
5420
0
}
5421
5422
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
5423
311
{
5424
311
    ImGuiContext& g = *GImGui;
5425
311
    ImGuiWindow* parent_window = g.CurrentWindow;
5426
5427
311
    flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
5428
311
    flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag
5429
5430
    // Size
5431
311
    const ImVec2 content_avail = GetContentRegionAvail();
5432
311
    ImVec2 size = ImFloor(size_arg);
5433
311
    const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
5434
311
    if (size.x <= 0.0f)
5435
239
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
5436
311
    if (size.y <= 0.0f)
5437
224
        size.y = ImMax(content_avail.y + size.y, 4.0f);
5438
311
    SetNextWindowSize(size);
5439
5440
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5441
311
    const char* temp_window_name;
5442
311
    if (name)
5443
311
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5444
0
    else
5445
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5446
5447
311
    const float backup_border_size = g.Style.ChildBorderSize;
5448
311
    if (!border)
5449
193
        g.Style.ChildBorderSize = 0.0f;
5450
311
    bool ret = Begin(temp_window_name, NULL, flags);
5451
311
    g.Style.ChildBorderSize = backup_border_size;
5452
5453
311
    ImGuiWindow* child_window = g.CurrentWindow;
5454
311
    child_window->ChildId = id;
5455
311
    child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
5456
5457
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5458
    // While this is not really documented/defined, it seems that the expected thing to do.
5459
311
    if (child_window->BeginCount == 1)
5460
311
        parent_window->DC.CursorPos = child_window->Pos;
5461
5462
    // Process navigation-in immediately so NavInit can run on first frame
5463
311
    if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))
5464
0
    {
5465
0
        FocusWindow(child_window);
5466
0
        NavInitWindow(child_window, false);
5467
0
        SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5468
0
        g.ActiveIdSource = ImGuiInputSource_Nav;
5469
0
    }
5470
311
    return ret;
5471
311
}
5472
5473
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5474
311
{
5475
311
    ImGuiWindow* window = GetCurrentWindow();
5476
311
    return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
5477
311
}
5478
5479
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5480
0
{
5481
0
    IM_ASSERT(id != 0);
5482
0
    return BeginChildEx(NULL, id, size_arg, border, extra_flags);
5483
0
}
5484
5485
void ImGui::EndChild()
5486
311
{
5487
311
    ImGuiContext& g = *GImGui;
5488
311
    ImGuiWindow* window = g.CurrentWindow;
5489
5490
311
    IM_ASSERT(g.WithinEndChild == false);
5491
311
    IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5492
5493
311
    g.WithinEndChild = true;
5494
311
    if (window->BeginCount > 1)
5495
0
    {
5496
0
        End();
5497
0
    }
5498
311
    else
5499
311
    {
5500
311
        ImVec2 sz = window->Size;
5501
311
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
5502
239
            sz.x = ImMax(4.0f, sz.x);
5503
311
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
5504
224
            sz.y = ImMax(4.0f, sz.y);
5505
311
        End();
5506
5507
311
        ImGuiWindow* parent_window = g.CurrentWindow;
5508
311
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
5509
311
        ItemSize(sz);
5510
311
        if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
5511
79
        {
5512
79
            ItemAdd(bb, window->ChildId);
5513
79
            RenderNavHighlight(bb, window->ChildId);
5514
5515
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5516
79
            if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
5517
75
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5518
79
        }
5519
232
        else
5520
232
        {
5521
            // Not navigable into
5522
232
            ItemAdd(bb, 0);
5523
232
        }
5524
311
        if (g.HoveredWindow == window)
5525
0
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5526
311
    }
5527
311
    g.WithinEndChild = false;
5528
311
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5529
311
}
5530
5531
// Helper to create a child window / scrolling region that looks like a normal widget frame.
5532
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5533
0
{
5534
0
    ImGuiContext& g = *GImGui;
5535
0
    const ImGuiStyle& style = g.Style;
5536
0
    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5537
0
    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5538
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5539
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5540
0
    bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
5541
0
    PopStyleVar(3);
5542
0
    PopStyleColor();
5543
0
    return ret;
5544
0
}
5545
5546
void ImGui::EndChildFrame()
5547
0
{
5548
0
    EndChild();
5549
0
}
5550
5551
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5552
12
{
5553
12
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5554
12
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5555
12
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5556
12
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5557
12
}
5558
5559
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5560
180k
{
5561
180k
    ImGuiContext& g = *GImGui;
5562
180k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5563
180k
}
5564
5565
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5566
180k
{
5567
180k
    ImGuiID id = ImHashStr(name);
5568
180k
    return FindWindowByID(id);
5569
180k
}
5570
5571
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5572
0
{
5573
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5574
0
    window->ViewportPos = main_viewport->Pos;
5575
0
    if (settings->ViewportId)
5576
0
    {
5577
0
        window->ViewportId = settings->ViewportId;
5578
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5579
0
    }
5580
0
    window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5581
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5582
0
        window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
5583
0
    window->Collapsed = settings->Collapsed;
5584
0
    window->DockId = settings->DockId;
5585
0
    window->DockOrder = settings->DockOrder;
5586
0
}
5587
5588
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5589
180k
{
5590
180k
    ImGuiContext& g = *GImGui;
5591
5592
180k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5593
180k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5594
180k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5595
2
    {
5596
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5597
2
        g.WindowsFocusOrder.push_back(window);
5598
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5599
2
    }
5600
180k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5601
0
    {
5602
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5603
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5604
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5605
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5606
0
        window->FocusOrder = -1;
5607
0
    }
5608
180k
    window->IsExplicitChild = new_is_explicit_child;
5609
180k
}
5610
5611
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5612
3
{
5613
3
    ImGuiContext& g = *GImGui;
5614
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5615
5616
    // Create window the first time
5617
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5618
3
    window->Flags = flags;
5619
3
    g.WindowsById.SetVoidPtr(window->ID, window);
5620
5621
    // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5622
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5623
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5624
3
    window->ViewportPos = main_viewport->Pos;
5625
5626
    // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
5627
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5628
2
        if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
5629
0
        {
5630
            // Retrieve settings from .ini file
5631
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5632
0
            SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5633
0
            ApplyWindowSettings(window, settings);
5634
0
        }
5635
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5636
5637
3
    if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5638
0
    {
5639
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5640
0
        window->AutoFitOnlyGrows = false;
5641
0
    }
5642
3
    else
5643
3
    {
5644
3
        if (window->Size.x <= 0.0f)
5645
3
            window->AutoFitFramesX = 2;
5646
3
        if (window->Size.y <= 0.0f)
5647
3
            window->AutoFitFramesY = 2;
5648
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5649
3
    }
5650
5651
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5652
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5653
3
    else
5654
3
        g.Windows.push_back(window);
5655
5656
3
    return window;
5657
3
}
5658
5659
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5660
0
{
5661
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5662
0
}
5663
5664
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5665
360k
{
5666
360k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5667
360k
}
5668
5669
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5670
361k
{
5671
361k
    ImGuiContext& g = *GImGui;
5672
361k
    ImVec2 new_size = size_desired;
5673
361k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5674
0
    {
5675
        // Using -1,-1 on either X/Y axis to preserve the current size.
5676
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5677
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5678
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5679
0
        if (g.NextWindowData.SizeCallback)
5680
0
        {
5681
0
            ImGuiSizeCallbackData data;
5682
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5683
0
            data.Pos = window->Pos;
5684
0
            data.CurrentSize = window->SizeFull;
5685
0
            data.DesiredSize = new_size;
5686
0
            g.NextWindowData.SizeCallback(&data);
5687
0
            new_size = data.DesiredSize;
5688
0
        }
5689
0
        new_size.x = IM_FLOOR(new_size.x);
5690
0
        new_size.y = IM_FLOOR(new_size.y);
5691
0
    }
5692
5693
    // Minimum size
5694
361k
    if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
5695
360k
    {
5696
360k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5697
360k
        new_size = ImMax(new_size, g.Style.WindowMinSize);
5698
360k
        const float minimum_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f);
5699
360k
        new_size.y = ImMax(new_size.y, minimum_height); // Reduce artifacts with very small windows
5700
360k
    }
5701
361k
    return new_size;
5702
361k
}
5703
5704
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5705
180k
{
5706
180k
    bool preserve_old_content_sizes = false;
5707
180k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5708
89.9k
        preserve_old_content_sizes = true;
5709
90.8k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
5710
0
        preserve_old_content_sizes = true;
5711
180k
    if (preserve_old_content_sizes)
5712
89.9k
    {
5713
89.9k
        *content_size_current = window->ContentSize;
5714
89.9k
        *content_size_ideal = window->ContentSizeIdeal;
5715
89.9k
        return;
5716
89.9k
    }
5717
5718
90.8k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
5719
90.8k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
5720
90.8k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
5721
90.8k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
5722
90.8k
}
5723
5724
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
5725
180k
{
5726
180k
    ImGuiContext& g = *GImGui;
5727
180k
    ImGuiStyle& style = g.Style;
5728
180k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
5729
180k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
5730
180k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
5731
180k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
5732
180k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
5733
0
    {
5734
        // Tooltip always resize
5735
0
        return size_desired;
5736
0
    }
5737
180k
    else
5738
180k
    {
5739
        // Maximum window size is determined by the viewport size or monitor size
5740
180k
        const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
5741
180k
        const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
5742
180k
        ImVec2 size_min = style.WindowMinSize;
5743
180k
        if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5744
0
            size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
5745
5746
180k
        ImVec2 avail_size = window->Viewport->WorkSize;
5747
180k
        if (window->ViewportOwned)
5748
0
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
5749
180k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
5750
180k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
5751
0
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
5752
180k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
5753
5754
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
5755
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
5756
180k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5757
180k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
5758
180k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
5759
180k
        if (will_have_scrollbar_x)
5760
311
            size_auto_fit.y += style.ScrollbarSize;
5761
180k
        if (will_have_scrollbar_y)
5762
26
            size_auto_fit.x += style.ScrollbarSize;
5763
180k
        return size_auto_fit;
5764
180k
    }
5765
180k
}
5766
5767
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
5768
0
{
5769
0
    ImVec2 size_contents_current;
5770
0
    ImVec2 size_contents_ideal;
5771
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
5772
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
5773
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5774
0
    return size_final;
5775
0
}
5776
5777
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
5778
90.8k
{
5779
90.8k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
5780
0
        return ImGuiCol_PopupBg;
5781
90.8k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
5782
311
        return ImGuiCol_ChildBg;
5783
90.5k
    return ImGuiCol_WindowBg;
5784
90.8k
}
5785
5786
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
5787
0
{
5788
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
5789
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
5790
0
    ImVec2 size_expected = pos_max - pos_min;
5791
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
5792
0
    *out_pos = pos_min;
5793
0
    if (corner_norm.x == 0.0f)
5794
0
        out_pos->x -= (size_constrained.x - size_expected.x);
5795
0
    if (corner_norm.y == 0.0f)
5796
0
        out_pos->y -= (size_constrained.y - size_expected.y);
5797
0
    *out_size = size_constrained;
5798
0
}
5799
5800
// Data for resizing from corner
5801
struct ImGuiResizeGripDef
5802
{
5803
    ImVec2  CornerPosN;
5804
    ImVec2  InnerDir;
5805
    int     AngleMin12, AngleMax12;
5806
};
5807
static const ImGuiResizeGripDef resize_grip_def[4] =
5808
{
5809
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
5810
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
5811
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
5812
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
5813
};
5814
5815
// Data for resizing from borders
5816
struct ImGuiResizeBorderDef
5817
{
5818
    ImVec2 InnerDir;
5819
    ImVec2 SegmentN1, SegmentN2;
5820
    float  OuterAngle;
5821
};
5822
static const ImGuiResizeBorderDef resize_border_def[4] =
5823
{
5824
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
5825
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
5826
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
5827
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
5828
};
5829
5830
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
5831
0
{
5832
0
    ImRect rect = window->Rect();
5833
0
    if (thickness == 0.0f)
5834
0
        rect.Max -= ImVec2(1, 1);
5835
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
5836
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
5837
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
5838
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
5839
0
    IM_ASSERT(0);
5840
0
    return ImRect();
5841
0
}
5842
5843
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
5844
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
5845
0
{
5846
0
    IM_ASSERT(n >= 0 && n < 4);
5847
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5848
0
    id = ImHashStr("#RESIZE", 0, id);
5849
0
    id = ImHashData(&n, sizeof(int), id);
5850
0
    return id;
5851
0
}
5852
5853
// Borders (Left, Right, Up, Down)
5854
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
5855
0
{
5856
0
    IM_ASSERT(dir >= 0 && dir < 4);
5857
0
    int n = (int)dir + 4;
5858
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5859
0
    id = ImHashStr("#RESIZE", 0, id);
5860
0
    id = ImHashData(&n, sizeof(int), id);
5861
0
    return id;
5862
0
}
5863
5864
// Handle resize for: Resize Grips, Borders, Gamepad
5865
// Return true when using auto-fit (double-click on resize grip)
5866
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
5867
90.8k
{
5868
90.8k
    ImGuiContext& g = *GImGui;
5869
90.8k
    ImGuiWindowFlags flags = window->Flags;
5870
5871
90.8k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
5872
313
        return false;
5873
90.5k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
5874
90.2k
        return false;
5875
5876
309
    bool ret_auto_fit = false;
5877
309
    const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
5878
309
    const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
5879
309
    const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
5880
309
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
5881
5882
309
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
5883
309
    ImVec2 size_target(FLT_MAX, FLT_MAX);
5884
5885
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
5886
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
5887
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
5888
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
5889
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
5890
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
5891
309
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
5892
309
    if (clip_with_viewport_rect)
5893
309
        window->ClipRect = window->Viewport->GetMainRect();
5894
5895
    // Resize grips and borders are on layer 1
5896
309
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
5897
5898
    // Manual resize grips
5899
309
    PushID("#RESIZE");
5900
618
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
5901
309
    {
5902
309
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
5903
309
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
5904
5905
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
5906
309
        bool hovered, held;
5907
309
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
5908
309
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
5909
309
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
5910
309
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
5911
309
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
5912
309
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
5913
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
5914
309
        if (hovered || held)
5915
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
5916
5917
309
        if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
5918
0
        {
5919
            // Manual auto-fit when double-clicking
5920
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5921
0
            ret_auto_fit = true;
5922
0
            ClearActiveID();
5923
0
        }
5924
309
        else if (held)
5925
0
        {
5926
            // Resize from any of the four corners
5927
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
5928
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
5929
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
5930
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
5931
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
5932
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
5933
0
        }
5934
5935
        // Only lower-left grip is visible before hovering/activating
5936
309
        if (resize_grip_n == 0 || held || hovered)
5937
309
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
5938
309
    }
5939
309
    for (int border_n = 0; border_n < resize_border_count; border_n++)
5940
0
    {
5941
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
5942
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
5943
5944
0
        bool hovered, held;
5945
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
5946
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
5947
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
5948
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
5949
        //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
5950
0
        if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
5951
0
        {
5952
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
5953
0
            if (held)
5954
0
                *border_held = border_n;
5955
0
        }
5956
0
        if (held)
5957
0
        {
5958
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
5959
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left  ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up   ? visibility_rect.Max.y : +FLT_MAX);
5960
0
            ImVec2 border_target = window->Pos;
5961
0
            border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
5962
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
5963
0
            CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
5964
0
        }
5965
0
    }
5966
309
    PopID();
5967
5968
    // Restore nav layer
5969
309
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
5970
5971
    // Navigation resize (keyboard/gamepad)
5972
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
5973
    // Not even sure the callback works here.
5974
309
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
5975
0
    {
5976
0
        ImVec2 nav_resize_dir;
5977
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
5978
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
5979
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
5980
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
5981
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
5982
0
        {
5983
0
            const float NAV_RESIZE_SPEED = 600.0f;
5984
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
5985
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
5986
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, visibility_rect.Min - window->Pos - window->Size); // We need Pos+Size >= visibility_rect.Min, so Size >= visibility_rect.Min - Pos, so size_delta >= visibility_rect.Min - window->Pos - window->Size
5987
0
            g.NavWindowingToggleLayer = false;
5988
0
            g.NavDisableMouseHover = true;
5989
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
5990
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaSize);
5991
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
5992
0
            {
5993
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
5994
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
5995
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
5996
0
            }
5997
0
        }
5998
0
    }
5999
6000
    // Apply back modified position/size to window
6001
309
    if (size_target.x != FLT_MAX)
6002
0
    {
6003
0
        window->SizeFull = size_target;
6004
0
        MarkIniSettingsDirty(window);
6005
0
    }
6006
309
    if (pos_target.x != FLT_MAX)
6007
0
    {
6008
0
        window->Pos = ImFloor(pos_target);
6009
0
        MarkIniSettingsDirty(window);
6010
0
    }
6011
6012
309
    window->Size = window->SizeFull;
6013
309
    return ret_auto_fit;
6014
90.5k
}
6015
6016
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6017
180k
{
6018
180k
    ImGuiContext& g = *GImGui;
6019
180k
    ImVec2 size_for_clamping = window->Size;
6020
180k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6021
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6022
180k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6023
180k
}
6024
6025
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6026
90.8k
{
6027
90.8k
    ImGuiContext& g = *GImGui;
6028
90.8k
    float rounding = window->WindowRounding;
6029
90.8k
    float border_size = window->WindowBorderSize;
6030
90.8k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6031
90.6k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6032
6033
90.8k
    int border_held = window->ResizeBorderHeld;
6034
90.8k
    if (border_held != -1)
6035
0
    {
6036
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_held];
6037
0
        ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
6038
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6039
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6040
0
        window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
6041
0
    }
6042
90.8k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6043
0
    {
6044
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6045
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6046
0
    }
6047
90.8k
}
6048
6049
// Draw background and borders
6050
// Draw and handle scrollbars
6051
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6052
180k
{
6053
180k
    ImGuiContext& g = *GImGui;
6054
180k
    ImGuiStyle& style = g.Style;
6055
180k
    ImGuiWindowFlags flags = window->Flags;
6056
6057
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6058
180k
    IM_ASSERT(window->BeginCount == 0);
6059
180k
    window->SkipItems = false;
6060
6061
    // Draw window + handle manual resize
6062
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6063
180k
    const float window_rounding = window->WindowRounding;
6064
180k
    const float window_border_size = window->WindowBorderSize;
6065
180k
    if (window->Collapsed)
6066
89.9k
    {
6067
        // Title bar only
6068
89.9k
        const float backup_border_size = style.FrameBorderSize;
6069
89.9k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6070
89.9k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6071
89.9k
        if (window->ViewportOwned)
6072
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6073
89.9k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6074
89.9k
        g.Style.FrameBorderSize = backup_border_size;
6075
89.9k
    }
6076
90.8k
    else
6077
90.8k
    {
6078
        // Window background
6079
90.8k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6080
90.8k
        {
6081
90.8k
            bool is_docking_transparent_payload = false;
6082
90.8k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6083
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6084
0
                    is_docking_transparent_payload = true;
6085
6086
90.8k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6087
90.8k
            if (window->ViewportOwned)
6088
0
            {
6089
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6090
0
                if (is_docking_transparent_payload)
6091
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6092
0
            }
6093
90.8k
            else
6094
90.8k
            {
6095
                // Adjust alpha. For docking
6096
90.8k
                bool override_alpha = false;
6097
90.8k
                float alpha = 1.0f;
6098
90.8k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6099
0
                {
6100
0
                    alpha = g.NextWindowData.BgAlphaVal;
6101
0
                    override_alpha = true;
6102
0
                }
6103
90.8k
                if (is_docking_transparent_payload)
6104
0
                {
6105
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6106
0
                    override_alpha = true;
6107
0
                }
6108
90.8k
                if (override_alpha)
6109
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6110
90.8k
            }
6111
6112
            // Render, for docked windows and host windows we ensure bg goes before decorations
6113
90.8k
            if (window->DockIsActive)
6114
0
                window->DockNode->LastBgColor = bg_col;
6115
90.8k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6116
90.8k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6117
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6118
90.8k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6119
90.8k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6120
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6121
90.8k
        }
6122
90.8k
        if (window->DockIsActive)
6123
0
            window->DockNode->IsBgDrawnThisFrame = true;
6124
6125
        // Title bar
6126
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6127
        // in order for their pos/size to be matching their undocking state.)
6128
90.8k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6129
90.5k
        {
6130
90.5k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6131
90.5k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6132
90.5k
        }
6133
6134
        // Menu bar
6135
90.8k
        if (flags & ImGuiWindowFlags_MenuBar)
6136
0
        {
6137
0
            ImRect menu_bar_rect = window->MenuBarRect();
6138
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6139
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6140
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6141
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6142
0
        }
6143
6144
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6145
90.8k
        ImGuiDockNode* node = window->DockNode;
6146
90.8k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6147
0
        {
6148
0
            float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
6149
0
            float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
6150
0
            ImVec2 p = node->Pos;
6151
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6152
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6153
0
            KeepAliveID(unhide_id);
6154
0
            bool hovered, held;
6155
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6156
0
                node->WantHiddenTabBarToggle = true;
6157
0
            else if (held && IsMouseDragging(0))
6158
0
                StartMouseMovingWindowOrNode(window, node, true);
6159
6160
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6161
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6162
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6163
0
        }
6164
6165
        // Scrollbars
6166
90.8k
        if (window->ScrollbarX)
6167
311
            Scrollbar(ImGuiAxis_X);
6168
90.8k
        if (window->ScrollbarY)
6169
97
            Scrollbar(ImGuiAxis_Y);
6170
6171
        // Render resize grips (after their input handling so we don't have a frame of latency)
6172
90.8k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6173
90.5k
        {
6174
181k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6175
90.5k
            {
6176
90.5k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6177
90.5k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6178
90.5k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6179
90.5k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6180
90.5k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6181
90.5k
                window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
6182
90.5k
            }
6183
90.5k
        }
6184
6185
        // Borders (for dock node host they will be rendered over after the tab bar)
6186
90.8k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6187
90.8k
            RenderWindowOuterBorders(window);
6188
90.8k
    }
6189
180k
}
6190
6191
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6192
// Render title text, collapse button, close button
6193
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6194
180k
{
6195
180k
    ImGuiContext& g = *GImGui;
6196
180k
    ImGuiStyle& style = g.Style;
6197
180k
    ImGuiWindowFlags flags = window->Flags;
6198
6199
180k
    const bool has_close_button = (p_open != NULL);
6200
180k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6201
6202
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6203
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6204
180k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6205
180k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6206
180k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6207
6208
    // Layout buttons
6209
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6210
180k
    float pad_l = style.FramePadding.x;
6211
180k
    float pad_r = style.FramePadding.x;
6212
180k
    float button_sz = g.FontSize;
6213
180k
    ImVec2 close_button_pos;
6214
180k
    ImVec2 collapse_button_pos;
6215
180k
    if (has_close_button)
6216
0
    {
6217
0
        pad_r += button_sz;
6218
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6219
0
    }
6220
180k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6221
0
    {
6222
0
        pad_r += button_sz;
6223
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6224
0
    }
6225
180k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6226
180k
    {
6227
180k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
6228
180k
        pad_l += button_sz;
6229
180k
    }
6230
6231
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6232
180k
    if (has_collapse_button)
6233
180k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6234
7
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6235
6236
    // Close button
6237
180k
    if (has_close_button)
6238
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6239
0
            *p_open = false;
6240
6241
180k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6242
180k
    g.CurrentItemFlags = item_flags_backup;
6243
6244
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6245
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6246
180k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6247
180k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6248
6249
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6250
    // while uncentered title text will still reach edges correctly.
6251
180k
    if (pad_l > style.FramePadding.x)
6252
180k
        pad_l += g.Style.ItemInnerSpacing.x;
6253
180k
    if (pad_r > style.FramePadding.x)
6254
0
        pad_r += g.Style.ItemInnerSpacing.x;
6255
180k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6256
0
    {
6257
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6258
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6259
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6260
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6261
0
    }
6262
6263
180k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6264
180k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6265
180k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6266
0
    {
6267
0
        ImVec2 marker_pos;
6268
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6269
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6270
0
        if (marker_pos.x > layout_r.Min.x)
6271
0
        {
6272
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6273
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6274
0
        }
6275
0
    }
6276
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6277
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6278
180k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6279
180k
}
6280
6281
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6282
180k
{
6283
180k
    window->ParentWindow = parent_window;
6284
180k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6285
180k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6286
311
    {
6287
311
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6288
311
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6289
311
            window->RootWindow = parent_window->RootWindow;
6290
311
    }
6291
180k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6292
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6293
180k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6294
311
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6295
180k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6296
0
    {
6297
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6298
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6299
0
    }
6300
180k
}
6301
6302
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6303
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6304
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6305
// - Window             // FindBlockingModal() returns Modal1
6306
//   - Window           //                  .. returns Modal1
6307
//   - Modal1           //                  .. returns Modal2
6308
//      - Window        //                  .. returns Modal2
6309
//          - Window    //                  .. returns Modal2
6310
//          - Modal2    //                  .. returns Modal2
6311
static ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6312
0
{
6313
0
    ImGuiContext& g = *GImGui;
6314
0
    if (g.OpenPopupStack.Size <= 0)
6315
0
        return NULL;
6316
6317
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6318
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
6319
0
    {
6320
0
        ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;
6321
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6322
0
            continue;
6323
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6324
0
            continue;
6325
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window is rendered over last modal, no render order change needed.
6326
0
            break;
6327
0
        for (ImGuiWindow* parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow)
6328
0
            if (IsWindowWithinBeginStackOf(window, parent))
6329
0
                return popup_window;                                // Place window above its begin stack parent.
6330
0
    }
6331
0
    return NULL;
6332
0
}
6333
6334
// Push a new Dear ImGui window to add widgets to.
6335
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6336
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6337
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6338
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6339
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6340
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6341
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6342
180k
{
6343
180k
    ImGuiContext& g = *GImGui;
6344
180k
    const ImGuiStyle& style = g.Style;
6345
180k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6346
180k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6347
180k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6348
6349
    // Find or create
6350
180k
    ImGuiWindow* window = FindWindowByName(name);
6351
180k
    const bool window_just_created = (window == NULL);
6352
180k
    if (window_just_created)
6353
3
        window = CreateNewWindow(name, flags);
6354
6355
    // Automatically disable manual moving/resizing when NoInputs is set
6356
180k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6357
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6358
6359
180k
    if (flags & ImGuiWindowFlags_NavFlattened)
6360
180k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6361
6362
180k
    const int current_frame = g.FrameCount;
6363
180k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6364
180k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6365
6366
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6367
180k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6368
180k
    if (flags & ImGuiWindowFlags_Popup)
6369
0
    {
6370
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6371
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6372
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6373
0
    }
6374
6375
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6376
180k
    const bool window_was_appearing = window->Appearing;
6377
180k
    if (first_begin_of_the_frame)
6378
180k
    {
6379
180k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6380
180k
        window->Appearing = window_just_activated_by_user;
6381
180k
        if (window->Appearing)
6382
6
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6383
180k
        window->FlagsPreviousFrame = window->Flags;
6384
180k
        window->Flags = (ImGuiWindowFlags)flags;
6385
180k
        window->LastFrameActive = current_frame;
6386
180k
        window->LastTimeActive = (float)g.Time;
6387
180k
        window->BeginOrderWithinParent = 0;
6388
180k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6389
180k
    }
6390
0
    else
6391
0
    {
6392
0
        flags = window->Flags;
6393
0
    }
6394
6395
    // Docking
6396
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6397
180k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6398
180k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6399
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6400
180k
    if (first_begin_of_the_frame)
6401
180k
    {
6402
180k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6403
180k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6404
180k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6405
180k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6406
180k
        if (has_dock_node || new_auto_dock_node)
6407
0
        {
6408
0
            BeginDocked(window, p_open);
6409
0
            flags = window->Flags;
6410
0
            if (window->DockIsActive)
6411
0
            {
6412
0
                IM_ASSERT(window->DockNode != NULL);
6413
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6414
0
            }
6415
6416
            // Amend the Appearing flag
6417
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6418
0
            {
6419
0
                window->Appearing = true;
6420
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6421
0
            }
6422
0
        }
6423
180k
        else
6424
180k
        {
6425
180k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6426
180k
        }
6427
180k
    }
6428
6429
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6430
180k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6431
180k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6432
180k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6433
6434
    // We allow window memory to be compacted so recreate the base stack when needed.
6435
180k
    if (window->IDStack.Size == 0)
6436
0
        window->IDStack.push_back(window->ID);
6437
6438
    // Add to stack
6439
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6440
180k
    g.CurrentWindow = window;
6441
180k
    ImGuiWindowStackData window_stack_data;
6442
180k
    window_stack_data.Window = window;
6443
180k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6444
180k
    window_stack_data.StackSizesOnBegin.SetToCurrentState();
6445
180k
    g.CurrentWindowStack.push_back(window_stack_data);
6446
180k
    if (flags & ImGuiWindowFlags_ChildMenu)
6447
0
        g.BeginMenuCount++;
6448
6449
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6450
180k
    if (first_begin_of_the_frame)
6451
180k
    {
6452
180k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6453
180k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6454
180k
    }
6455
6456
    // Add to focus scope stack
6457
180k
    PushFocusScope(window->ID);
6458
180k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6459
180k
    g.CurrentWindow = NULL;
6460
6461
    // Add to popup stack
6462
180k
    if (flags & ImGuiWindowFlags_Popup)
6463
0
    {
6464
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6465
0
        popup_ref.Window = window;
6466
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6467
0
        g.BeginPopupStack.push_back(popup_ref);
6468
0
        window->PopupId = popup_ref.PopupId;
6469
0
    }
6470
6471
    // Process SetNextWindow***() calls
6472
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6473
180k
    bool window_pos_set_by_api = false;
6474
180k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6475
180k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6476
0
    {
6477
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6478
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6479
0
        {
6480
            // May be processed on the next frame if this is our first frame and we are measuring size
6481
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6482
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6483
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6484
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6485
0
        }
6486
0
        else
6487
0
        {
6488
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6489
0
        }
6490
0
    }
6491
180k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6492
90.5k
    {
6493
90.5k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6494
90.5k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6495
90.5k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6496
90.5k
    }
6497
180k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6498
0
    {
6499
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6500
0
        {
6501
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6502
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6503
0
        }
6504
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6505
0
        {
6506
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6507
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6508
0
        }
6509
0
    }
6510
180k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6511
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6512
180k
    else if (first_begin_of_the_frame)
6513
180k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6514
180k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6515
0
        window->WindowClass = g.NextWindowData.WindowClass;
6516
180k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6517
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6518
180k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6519
0
        FocusWindow(window);
6520
180k
    if (window->Appearing)
6521
6
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6522
6523
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6524
180k
    if (first_begin_of_the_frame)
6525
180k
    {
6526
        // Initialize
6527
180k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6528
180k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6529
180k
        window->Active = true;
6530
180k
        window->HasCloseButton = (p_open != NULL);
6531
180k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6532
180k
        window->IDStack.resize(1);
6533
180k
        window->DrawList->_ResetForNewFrame();
6534
180k
        window->DC.CurrentTableIdx = -1;
6535
180k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6536
0
        {
6537
0
            window->DrawList->ChannelsSplit(2);
6538
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6539
0
        }
6540
6541
        // Restore buffer capacity when woken from a compacted state, to avoid
6542
180k
        if (window->MemoryCompacted)
6543
0
            GcAwakeTransientWindowBuffers(window);
6544
6545
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6546
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6547
180k
        bool window_title_visible_elsewhere = false;
6548
180k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6549
0
            window_title_visible_elsewhere = true;
6550
180k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6551
0
            window_title_visible_elsewhere = true;
6552
180k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6553
0
        {
6554
0
            size_t buf_len = (size_t)window->NameBufLen;
6555
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6556
0
            window->NameBufLen = (int)buf_len;
6557
0
        }
6558
6559
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6560
6561
        // Update contents size from last frame for auto-fitting (or use explicit size)
6562
180k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6563
6564
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6565
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6566
        // it has a single usage before this code block and may be set below before it is finally checked.
6567
180k
        if (window->HiddenFramesCanSkipItems > 0)
6568
0
            window->HiddenFramesCanSkipItems--;
6569
180k
        if (window->HiddenFramesCannotSkipItems > 0)
6570
2
            window->HiddenFramesCannotSkipItems--;
6571
180k
        if (window->HiddenFramesForRenderOnly > 0)
6572
0
            window->HiddenFramesForRenderOnly--;
6573
6574
        // Hide new windows for one frame until they calculate their size
6575
180k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6576
1
            window->HiddenFramesCannotSkipItems = 1;
6577
6578
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6579
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6580
180k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6581
0
        {
6582
0
            window->HiddenFramesCannotSkipItems = 1;
6583
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6584
0
            {
6585
0
                if (!window_size_x_set_by_api)
6586
0
                    window->Size.x = window->SizeFull.x = 0.f;
6587
0
                if (!window_size_y_set_by_api)
6588
0
                    window->Size.y = window->SizeFull.y = 0.f;
6589
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6590
0
            }
6591
0
        }
6592
6593
        // SELECT VIEWPORT
6594
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6595
6596
180k
        WindowSelectViewport(window);
6597
180k
        SetCurrentViewport(window, window->Viewport);
6598
180k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6599
180k
        SetCurrentWindow(window);
6600
180k
        flags = window->Flags;
6601
6602
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6603
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6604
6605
180k
        if (flags & ImGuiWindowFlags_ChildWindow)
6606
311
            window->WindowBorderSize = style.ChildBorderSize;
6607
180k
        else
6608
180k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6609
180k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
6610
193
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6611
180k
        else
6612
180k
            window->WindowPadding = style.WindowPadding;
6613
6614
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6615
180k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
6616
180k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6617
6618
180k
        bool use_current_size_for_scrollbar_x = window_just_created;
6619
180k
        bool use_current_size_for_scrollbar_y = window_just_created;
6620
6621
        // Collapse window by double-clicking on title bar
6622
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
6623
180k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
6624
180k
        {
6625
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
6626
180k
            ImRect title_bar_rect = window->TitleBarRect();
6627
180k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
6628
0
                window->WantCollapseToggle = true;
6629
180k
            if (window->WantCollapseToggle)
6630
7
            {
6631
7
                window->Collapsed = !window->Collapsed;
6632
7
                if (!window->Collapsed)
6633
3
                    use_current_size_for_scrollbar_y = true;
6634
7
                MarkIniSettingsDirty(window);
6635
7
            }
6636
180k
        }
6637
311
        else
6638
311
        {
6639
311
            window->Collapsed = false;
6640
311
        }
6641
180k
        window->WantCollapseToggle = false;
6642
6643
        // SIZE
6644
6645
        // Outer Decoration Sizes
6646
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
6647
180k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
6648
180k
        window->DecoOuterSizeX1 = 0.0f;
6649
180k
        window->DecoOuterSizeX2 = 0.0f;
6650
180k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
6651
180k
        window->DecoOuterSizeY2 = 0.0f;
6652
180k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
6653
6654
        // Calculate auto-fit size, handle automatic resize
6655
180k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
6656
180k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6657
0
        {
6658
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6659
0
            if (!window_size_x_set_by_api)
6660
0
            {
6661
0
                window->SizeFull.x = size_auto_fit.x;
6662
0
                use_current_size_for_scrollbar_x = true;
6663
0
            }
6664
0
            if (!window_size_y_set_by_api)
6665
0
            {
6666
0
                window->SizeFull.y = size_auto_fit.y;
6667
0
                use_current_size_for_scrollbar_y = true;
6668
0
            }
6669
0
        }
6670
180k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6671
2
        {
6672
            // Auto-fit may only grow window during the first few frames
6673
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6674
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6675
2
            {
6676
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
6677
2
                use_current_size_for_scrollbar_x = true;
6678
2
            }
6679
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6680
2
            {
6681
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
6682
2
                use_current_size_for_scrollbar_y = true;
6683
2
            }
6684
2
            if (!window->Collapsed)
6685
2
                MarkIniSettingsDirty(window);
6686
2
        }
6687
6688
        // Apply minimum/maximum window size constraints and final size
6689
180k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
6690
180k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
6691
6692
        // POSITION
6693
6694
        // Popup latch its initial position, will position itself when it appears next frame
6695
180k
        if (window_just_activated_by_user)
6696
6
        {
6697
6
            window->AutoPosLastDirection = ImGuiDir_None;
6698
6
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
6699
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
6700
6
        }
6701
6702
        // Position child window
6703
180k
        if (flags & ImGuiWindowFlags_ChildWindow)
6704
311
        {
6705
311
            IM_ASSERT(parent_window && parent_window->Active);
6706
311
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
6707
311
            parent_window->DC.ChildWindows.push_back(window);
6708
311
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
6709
311
                window->Pos = parent_window->DC.CursorPos;
6710
311
        }
6711
6712
180k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
6713
180k
        if (window_pos_with_pivot)
6714
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
6715
180k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
6716
0
            window->Pos = FindBestWindowPosForPopup(window);
6717
180k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
6718
0
            window->Pos = FindBestWindowPosForPopup(window);
6719
180k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
6720
0
            window->Pos = FindBestWindowPosForPopup(window);
6721
6722
        // Late create viewport if we don't fit within our current host viewport.
6723
180k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized))
6724
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
6725
0
            {
6726
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
6727
                //ImGuiViewport* old_viewport = window->Viewport;
6728
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
6729
6730
                // FIXME-DPI
6731
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
6732
0
                SetCurrentViewport(window, window->Viewport);
6733
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6734
0
                SetCurrentWindow(window);
6735
0
            }
6736
6737
180k
        if (window->ViewportOwned)
6738
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
6739
6740
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
6741
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
6742
180k
        ImRect viewport_rect(window->Viewport->GetMainRect());
6743
180k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
6744
180k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
6745
180k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
6746
6747
        // Clamp position/size so window stays visible within its viewport or monitor
6748
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
6749
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
6750
180k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
6751
180k
        {
6752
180k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
6753
180k
            {
6754
180k
                ClampWindowPos(window, visibility_rect);
6755
180k
            }
6756
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
6757
0
            {
6758
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
6759
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
6760
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
6761
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
6762
0
                ClampWindowPos(window, visibility_rect);
6763
0
            }
6764
180k
        }
6765
180k
        window->Pos = ImFloor(window->Pos);
6766
6767
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
6768
        // Large values tend to lead to variety of artifacts and are not recommended.
6769
180k
        if (window->ViewportOwned || window->DockIsActive)
6770
0
            window->WindowRounding = 0.0f;
6771
180k
        else
6772
180k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
6773
6774
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
6775
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6776
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
6777
6778
        // Apply window focus (new and reactivated windows are moved to front)
6779
180k
        bool want_focus = false;
6780
180k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
6781
6
        {
6782
6
            if (flags & ImGuiWindowFlags_Popup)
6783
0
                want_focus = true;
6784
6
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
6785
2
                want_focus = true;
6786
6787
6
            ImGuiWindow* modal = GetTopMostPopupModal();
6788
6
            if (modal != NULL && !IsWindowWithinBeginStackOf(window, modal))
6789
0
            {
6790
                // Avoid focusing a window that is created outside of active modal. This will prevent active modal from being closed.
6791
                // Since window is not focused it would reappear at the same display position like the last time it was visible.
6792
                // In case of completely new windows it would go to the top (over current modal), but input to such window would still be blocked by modal.
6793
                // Position window behind a modal that is not a begin-parent of this window.
6794
0
                want_focus = false;
6795
0
                if (window == window->RootWindow)
6796
0
                {
6797
0
                    ImGuiWindow* blocking_modal = FindBlockingModal(window);
6798
0
                    IM_ASSERT(blocking_modal != NULL);
6799
0
                    BringWindowToDisplayBehind(window, blocking_modal);
6800
0
                }
6801
0
            }
6802
6
        }
6803
6804
        // [Test Engine] Register whole window in the item system
6805
#ifdef IMGUI_ENABLE_TEST_ENGINE
6806
        if (g.TestEngineHookItems)
6807
        {
6808
            IM_ASSERT(window->IDStack.Size == 1);
6809
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
6810
            IMGUI_TEST_ENGINE_ITEM_ADD(window->Rect(), window->ID);
6811
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
6812
            window->IDStack.Size = 1;
6813
        }
6814
#endif
6815
6816
        // Decide if we are going to handle borders and resize grips
6817
180k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
6818
6819
        // Handle manual resize: Resize Grips, Borders, Gamepad
6820
180k
        int border_held = -1;
6821
180k
        ImU32 resize_grip_col[4] = {};
6822
180k
        const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
6823
180k
        const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6824
180k
        if (handle_borders_and_resize_grips && !window->Collapsed)
6825
90.8k
            if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
6826
0
                use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
6827
180k
        window->ResizeBorderHeld = (signed char)border_held;
6828
6829
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
6830
180k
        if (window->ViewportOwned)
6831
0
        {
6832
0
            if (!window->Viewport->PlatformRequestMove)
6833
0
                window->Viewport->Pos = window->Pos;
6834
0
            if (!window->Viewport->PlatformRequestResize)
6835
0
                window->Viewport->Size = window->Size;
6836
0
            window->Viewport->UpdateWorkRect();
6837
0
            viewport_rect = window->Viewport->GetMainRect();
6838
0
        }
6839
6840
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
6841
180k
        window->ViewportPos = window->Viewport->Pos;
6842
6843
        // SCROLLBAR VISIBILITY
6844
6845
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
6846
180k
        if (!window->Collapsed)
6847
90.8k
        {
6848
            // When reading the current size we need to read it after size constraints have been applied.
6849
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
6850
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
6851
90.8k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
6852
90.8k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
6853
90.8k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
6854
90.8k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
6855
90.8k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
6856
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
6857
90.8k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
6858
90.8k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
6859
90.8k
            if (window->ScrollbarX && !window->ScrollbarY)
6860
242
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
6861
90.8k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
6862
6863
            // Amend the partially filled window->DecorationXXX values.
6864
90.8k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
6865
90.8k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
6866
90.8k
        }
6867
6868
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
6869
        // Update various regions. Variables they depend on should be set above in this function.
6870
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
6871
6872
        // Outer rectangle
6873
        // Not affected by window border size. Used by:
6874
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
6875
        // - Begin() initial clipping rect for drawing window background and borders.
6876
        // - Begin() clipping whole child
6877
180k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
6878
180k
        const ImRect outer_rect = window->Rect();
6879
180k
        const ImRect title_bar_rect = window->TitleBarRect();
6880
180k
        window->OuterRectClipped = outer_rect;
6881
180k
        if (window->DockIsActive)
6882
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
6883
180k
        window->OuterRectClipped.ClipWith(host_rect);
6884
6885
        // Inner rectangle
6886
        // Not affected by window border size. Used by:
6887
        // - InnerClipRect
6888
        // - ScrollToRectEx()
6889
        // - NavUpdatePageUpPageDown()
6890
        // - Scrollbar()
6891
180k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
6892
180k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
6893
180k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
6894
180k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
6895
6896
        // Inner clipping rectangle.
6897
        // Will extend a little bit outside the normal work region.
6898
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
6899
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
6900
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
6901
        // Affected by window/frame border size. Used by:
6902
        // - Begin() initial clip rect
6903
180k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
6904
180k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
6905
180k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
6906
180k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
6907
180k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
6908
180k
        window->InnerClipRect.ClipWithFull(host_rect);
6909
6910
        // Default item width. Make it proportional to window size if window manually resizes
6911
180k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
6912
180k
            window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
6913
16
        else
6914
16
            window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
6915
6916
        // SCROLLING
6917
6918
        // Lock down maximum scrolling
6919
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
6920
        // for right/bottom aligned items without creating a scrollbar.
6921
180k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
6922
180k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
6923
6924
        // Apply scrolling
6925
180k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
6926
180k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
6927
180k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
6928
6929
        // DRAWING
6930
6931
        // Setup draw list and outer clipping rectangle
6932
180k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
6933
180k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
6934
180k
        PushClipRect(host_rect.Min, host_rect.Max, false);
6935
6936
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
6937
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
6938
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
6939
180k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
6940
180k
        if (is_undocked_or_docked_visible)
6941
180k
        {
6942
180k
            bool render_decorations_in_parent = false;
6943
180k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
6944
311
            {
6945
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
6946
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
6947
311
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
6948
311
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
6949
311
                bool parent_is_empty = parent_window->DrawList->VtxBuffer.Size > 0;
6950
311
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_is_empty && !previous_child_overlapping)
6951
311
                    render_decorations_in_parent = true;
6952
311
            }
6953
180k
            if (render_decorations_in_parent)
6954
311
                window->DrawList = parent_window->DrawList;
6955
6956
            // Handle title bar, scrollbar, resize grips and resize borders
6957
180k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
6958
180k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
6959
180k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
6960
6961
180k
            if (render_decorations_in_parent)
6962
311
                window->DrawList = &window->DrawListInst;
6963
180k
        }
6964
6965
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
6966
6967
        // Work rectangle.
6968
        // Affected by window padding and border size. Used by:
6969
        // - Columns() for right-most edge
6970
        // - TreeNode(), CollapsingHeader() for right-most edge
6971
        // - BeginTabBar() for right-most edge
6972
180k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
6973
180k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
6974
180k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
6975
180k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
6976
180k
        window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
6977
180k
        window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
6978
180k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
6979
180k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
6980
180k
        window->ParentWorkRect = window->WorkRect;
6981
6982
        // [LEGACY] Content Region
6983
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
6984
        // Used by:
6985
        // - Mouse wheel scrolling + many other things
6986
180k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
6987
180k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
6988
180k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
6989
180k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
6990
6991
        // Setup drawing context
6992
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
6993
180k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
6994
180k
        window->DC.GroupOffset.x = 0.0f;
6995
180k
        window->DC.ColumnsOffset.x = 0.0f;
6996
6997
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
6998
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
6999
180k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7000
180k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7001
180k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7002
180k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7003
180k
        window->DC.CursorPos = window->DC.CursorStartPos;
7004
180k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7005
180k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7006
180k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7007
180k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7008
180k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7009
180k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7010
7011
180k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7012
180k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7013
180k
        window->DC.NavLayersActiveMaskNext = 0x00;
7014
180k
        window->DC.NavHideHighlightOneFrame = false;
7015
180k
        window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
7016
7017
180k
        window->DC.MenuBarAppending = false;
7018
180k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7019
180k
        window->DC.TreeDepth = 0;
7020
180k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7021
180k
        window->DC.ChildWindows.resize(0);
7022
180k
        window->DC.StateStorage = &window->StateStorage;
7023
180k
        window->DC.CurrentColumns = NULL;
7024
180k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7025
180k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7026
7027
180k
        window->DC.ItemWidth = window->ItemWidthDefault;
7028
180k
        window->DC.TextWrapPos = -1.0f; // disabled
7029
180k
        window->DC.ItemWidthStack.resize(0);
7030
180k
        window->DC.TextWrapPosStack.resize(0);
7031
7032
180k
        if (window->AutoFitFramesX > 0)
7033
2
            window->AutoFitFramesX--;
7034
180k
        if (window->AutoFitFramesY > 0)
7035
2
            window->AutoFitFramesY--;
7036
7037
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7038
180k
        if (want_focus)
7039
2
        {
7040
2
            FocusWindow(window);
7041
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7042
2
        }
7043
7044
        // Close requested by platform window
7045
180k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7046
0
        {
7047
0
            if (!window->DockIsActive || window->DockTabIsVisible)
7048
0
            {
7049
0
                window->Viewport->PlatformRequestClose = false;
7050
0
                g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
7051
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' PlatformRequestClose\n", window->Name);
7052
0
                *p_open = false;
7053
0
            }
7054
0
        }
7055
7056
        // Title bar
7057
180k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7058
180k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7059
7060
        // Clear hit test shape every frame
7061
180k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7062
7063
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7064
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7065
        // Maybe we can support CTRL+C on every element?
7066
        /*
7067
        //if (g.NavWindow == window && g.ActiveId == 0)
7068
        if (g.ActiveId == window->MoveId)
7069
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7070
                LogToClipboard();
7071
        */
7072
7073
180k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7074
180k
        {
7075
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7076
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7077
180k
            if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift))
7078
59
                if ((window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7079
59
                    BeginDockableDragDropSource(window);
7080
7081
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7082
180k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7083
104
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7084
60
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7085
60
                        BeginDockableDragDropTarget(window);
7086
180k
        }
7087
7088
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7089
        // This is useful to allow creating context menus on title bar only, etc.
7090
180k
        if (window->DockIsActive)
7091
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7092
180k
        else
7093
180k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7094
7095
        // [DEBUG]
7096
180k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7097
180k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7098
0
            DebugLocateItemResolveWithLastItem();
7099
180k
#endif
7100
7101
        // [Test Engine] Register title bar / tab
7102
#ifdef IMGUI_ENABLE_TEST_ENGINE
7103
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7104
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.Rect, g.LastItemData.ID);
7105
#endif
7106
180k
    }
7107
0
    else
7108
0
    {
7109
        // Append
7110
0
        SetCurrentViewport(window, window->Viewport);
7111
0
        SetCurrentWindow(window);
7112
0
    }
7113
7114
180k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7115
180k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7116
7117
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7118
180k
    window->WriteAccessed = false;
7119
180k
    window->BeginCount++;
7120
180k
    g.NextWindowData.ClearFlags();
7121
7122
    // Update visibility
7123
180k
    if (first_begin_of_the_frame)
7124
180k
    {
7125
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7126
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7127
        // This is analogous to regular windows being hidden from one frame.
7128
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7129
180k
        if (window->DockIsActive && !window->DockTabIsVisible)
7130
0
        {
7131
0
            if (window->LastFrameJustFocused == g.FrameCount)
7132
0
                window->HiddenFramesCannotSkipItems = 1;
7133
0
            else
7134
0
                window->HiddenFramesCanSkipItems = 1;
7135
0
        }
7136
7137
180k
        if (flags & ImGuiWindowFlags_ChildWindow)
7138
311
        {
7139
            // Child window can be out of sight and have "negative" clip windows.
7140
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7141
311
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
7142
311
            if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
7143
311
            {
7144
311
                const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7145
311
                if (!g.LogEnabled && !nav_request)
7146
311
                    if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7147
0
                        window->HiddenFramesCanSkipItems = 1;
7148
311
            }
7149
7150
            // Hide along with parent or if parent is collapsed
7151
311
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7152
0
                window->HiddenFramesCanSkipItems = 1;
7153
311
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7154
1
                window->HiddenFramesCannotSkipItems = 1;
7155
311
        }
7156
7157
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7158
180k
        if (style.Alpha <= 0.0f)
7159
0
            window->HiddenFramesCanSkipItems = 1;
7160
7161
        // Update the Hidden flag
7162
180k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7163
180k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7164
7165
        // Disable inputs for requested number of frames
7166
180k
        if (window->DisableInputsFrames > 0)
7167
0
        {
7168
0
            window->DisableInputsFrames--;
7169
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7170
0
        }
7171
7172
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7173
180k
        bool skip_items = false;
7174
180k
        if (window->Collapsed || !window->Active || hidden_regular)
7175
89.9k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7176
89.9k
                skip_items = true;
7177
180k
        window->SkipItems = skip_items;
7178
7179
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7180
180k
        if (window->SkipItems)
7181
89.9k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7182
7183
        // Sanity check: there are two spots which can set Appearing = true
7184
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7185
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7186
180k
        if (window->SkipItems && !window->Appearing)
7187
180k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7188
180k
    }
7189
7190
180k
    return !window->SkipItems;
7191
180k
}
7192
7193
void ImGui::End()
7194
180k
{
7195
180k
    ImGuiContext& g = *GImGui;
7196
180k
    ImGuiWindow* window = g.CurrentWindow;
7197
7198
    // Error checking: verify that user hasn't called End() too many times!
7199
180k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7200
0
    {
7201
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7202
0
        return;
7203
0
    }
7204
180k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7205
7206
    // Error checking: verify that user doesn't directly call End() on a child window.
7207
180k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7208
180k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7209
7210
    // Close anything that is open
7211
180k
    if (window->DC.CurrentColumns)
7212
0
        EndColumns();
7213
180k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7214
180k
        PopClipRect();
7215
180k
    PopFocusScope();
7216
7217
    // Stop logging
7218
180k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7219
180k
        LogFinish();
7220
7221
180k
    if (window->DC.IsSetPos)
7222
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7223
7224
    // Docking: report contents sizes to parent to allow for auto-resize
7225
180k
    if (window->DockNode && window->DockTabIsVisible)
7226
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7227
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7228
7229
    // Pop from window stack
7230
180k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7231
180k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7232
0
        g.BeginMenuCount--;
7233
180k
    if (window->Flags & ImGuiWindowFlags_Popup)
7234
0
        g.BeginPopupStack.pop_back();
7235
180k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithCurrentState();
7236
180k
    g.CurrentWindowStack.pop_back();
7237
180k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7238
180k
    if (g.CurrentWindow)
7239
90.5k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7240
180k
}
7241
7242
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7243
176
{
7244
176
    ImGuiContext& g = *GImGui;
7245
176
    IM_ASSERT(window == window->RootWindow);
7246
7247
176
    const int cur_order = window->FocusOrder;
7248
176
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7249
176
    if (g.WindowsFocusOrder.back() == window)
7250
176
        return;
7251
7252
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7253
0
    for (int n = cur_order; n < new_order; n++)
7254
0
    {
7255
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7256
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7257
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7258
0
    }
7259
0
    g.WindowsFocusOrder[new_order] = window;
7260
0
    window->FocusOrder = (short)new_order;
7261
0
}
7262
7263
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7264
176
{
7265
176
    ImGuiContext& g = *GImGui;
7266
176
    ImGuiWindow* current_front_window = g.Windows.back();
7267
176
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7268
176
        return;
7269
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7270
0
        if (g.Windows[i] == window)
7271
0
        {
7272
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7273
0
            g.Windows[g.Windows.Size - 1] = window;
7274
0
            break;
7275
0
        }
7276
0
}
7277
7278
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7279
0
{
7280
0
    ImGuiContext& g = *GImGui;
7281
0
    if (g.Windows[0] == window)
7282
0
        return;
7283
0
    for (int i = 0; i < g.Windows.Size; i++)
7284
0
        if (g.Windows[i] == window)
7285
0
        {
7286
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7287
0
            g.Windows[0] = window;
7288
0
            break;
7289
0
        }
7290
0
}
7291
7292
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7293
0
{
7294
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7295
0
    ImGuiContext& g = *GImGui;
7296
0
    window = window->RootWindow;
7297
0
    behind_window = behind_window->RootWindow;
7298
0
    int pos_wnd = FindWindowDisplayIndex(window);
7299
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7300
0
    if (pos_wnd < pos_beh)
7301
0
    {
7302
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7303
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7304
0
        g.Windows[pos_beh - 1] = window;
7305
0
    }
7306
0
    else
7307
0
    {
7308
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7309
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7310
0
        g.Windows[pos_beh] = window;
7311
0
    }
7312
0
}
7313
7314
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7315
0
{
7316
0
    ImGuiContext& g = *GImGui;
7317
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7318
0
}
7319
7320
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7321
void ImGui::FocusWindow(ImGuiWindow* window)
7322
9.52k
{
7323
9.52k
    ImGuiContext& g = *GImGui;
7324
7325
9.52k
    if (g.NavWindow != window)
7326
104
    {
7327
104
        SetNavWindow(window);
7328
104
        if (window && g.NavDisableMouseHover)
7329
1
            g.NavMousePosDirty = true;
7330
104
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7331
104
        g.NavLayer = ImGuiNavLayer_Main;
7332
104
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7333
104
        g.NavIdIsAlive = false;
7334
7335
        // Close popups if any
7336
104
        ClosePopupsOverWindow(window, false);
7337
104
    }
7338
7339
    // Move the root window to the top of the pile
7340
9.52k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7341
9.52k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7342
9.52k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7343
9.52k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7344
9.52k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7345
7346
    // Steal active widgets. Some of the cases it triggers includes:
7347
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7348
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7349
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7350
9.52k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7351
37
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7352
14
            ClearActiveID();
7353
7354
    // Passing NULL allow to disable keyboard focus
7355
9.52k
    if (!window)
7356
9.34k
        return;
7357
176
    window->LastFrameJustFocused = g.FrameCount;
7358
7359
    // Select in dock node
7360
176
    if (dock_node && dock_node->TabBar)
7361
0
        dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7362
7363
    // Bring to front
7364
176
    BringWindowToFocusFront(focus_front_window);
7365
176
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7366
176
        BringWindowToDisplayFront(display_front_window);
7367
176
}
7368
7369
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
7370
0
{
7371
0
    ImGuiContext& g = *GImGui;
7372
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7373
0
    if (under_this_window != NULL)
7374
0
    {
7375
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7376
0
        int offset = -1;
7377
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7378
0
        {
7379
0
            under_this_window = under_this_window->ParentWindow;
7380
0
            offset = 0;
7381
0
        }
7382
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7383
0
    }
7384
0
    for (int i = start_idx; i >= 0; i--)
7385
0
    {
7386
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7387
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7388
0
        IM_ASSERT(window == window->RootWindow);
7389
0
        if (window != ignore_window && window->WasActive)
7390
0
            if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7391
0
            {
7392
                // FIXME-DOCK: This is failing (lagging by one frame) for docked windows.
7393
                // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7394
                // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7395
                // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7396
0
                ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
7397
0
                FocusWindow(focus_window);
7398
0
                return;
7399
0
            }
7400
0
    }
7401
0
    FocusWindow(NULL);
7402
0
}
7403
7404
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7405
void ImGui::SetCurrentFont(ImFont* font)
7406
90.2k
{
7407
90.2k
    ImGuiContext& g = *GImGui;
7408
90.2k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7409
90.2k
    IM_ASSERT(font->Scale > 0.0f);
7410
90.2k
    g.Font = font;
7411
90.2k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7412
90.2k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7413
7414
90.2k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7415
90.2k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7416
90.2k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7417
90.2k
    g.DrawListSharedData.Font = g.Font;
7418
90.2k
    g.DrawListSharedData.FontSize = g.FontSize;
7419
90.2k
}
7420
7421
void ImGui::PushFont(ImFont* font)
7422
0
{
7423
0
    ImGuiContext& g = *GImGui;
7424
0
    if (!font)
7425
0
        font = GetDefaultFont();
7426
0
    SetCurrentFont(font);
7427
0
    g.FontStack.push_back(font);
7428
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7429
0
}
7430
7431
void  ImGui::PopFont()
7432
0
{
7433
0
    ImGuiContext& g = *GImGui;
7434
0
    g.CurrentWindow->DrawList->PopTextureID();
7435
0
    g.FontStack.pop_back();
7436
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7437
0
}
7438
7439
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7440
311
{
7441
311
    ImGuiContext& g = *GImGui;
7442
311
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7443
311
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7444
311
    if (enabled)
7445
0
        item_flags |= option;
7446
311
    else
7447
311
        item_flags &= ~option;
7448
311
    g.CurrentItemFlags = item_flags;
7449
311
    g.ItemFlagsStack.push_back(item_flags);
7450
311
}
7451
7452
void ImGui::PopItemFlag()
7453
311
{
7454
311
    ImGuiContext& g = *GImGui;
7455
311
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7456
311
    g.ItemFlagsStack.pop_back();
7457
311
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7458
311
}
7459
7460
// BeginDisabled()/EndDisabled()
7461
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7462
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7463
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7464
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7465
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7466
void ImGui::BeginDisabled(bool disabled)
7467
0
{
7468
0
    ImGuiContext& g = *GImGui;
7469
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7470
0
    if (!was_disabled && disabled)
7471
0
    {
7472
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7473
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7474
0
    }
7475
0
    if (was_disabled || disabled)
7476
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7477
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7478
0
    g.DisabledStackSize++;
7479
0
}
7480
7481
void ImGui::EndDisabled()
7482
0
{
7483
0
    ImGuiContext& g = *GImGui;
7484
0
    IM_ASSERT(g.DisabledStackSize > 0);
7485
0
    g.DisabledStackSize--;
7486
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7487
    //PopItemFlag();
7488
0
    g.ItemFlagsStack.pop_back();
7489
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7490
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7491
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7492
0
}
7493
7494
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
7495
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
7496
311
{
7497
311
    PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
7498
311
}
7499
7500
void ImGui::PopAllowKeyboardFocus()
7501
311
{
7502
311
    PopItemFlag();
7503
311
}
7504
7505
void ImGui::PushButtonRepeat(bool repeat)
7506
0
{
7507
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7508
0
}
7509
7510
void ImGui::PopButtonRepeat()
7511
0
{
7512
0
    PopItemFlag();
7513
0
}
7514
7515
void ImGui::PushTextWrapPos(float wrap_pos_x)
7516
0
{
7517
0
    ImGuiWindow* window = GetCurrentWindow();
7518
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7519
0
    window->DC.TextWrapPos = wrap_pos_x;
7520
0
}
7521
7522
void ImGui::PopTextWrapPos()
7523
0
{
7524
0
    ImGuiWindow* window = GetCurrentWindow();
7525
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7526
0
    window->DC.TextWrapPosStack.pop_back();
7527
0
}
7528
7529
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7530
0
{
7531
0
    ImGuiWindow* last_window = NULL;
7532
0
    while (last_window != window)
7533
0
    {
7534
0
        last_window = window;
7535
0
        window = window->RootWindow;
7536
0
        if (popup_hierarchy)
7537
0
            window = window->RootWindowPopupTree;
7538
0
    if (dock_hierarchy)
7539
0
      window = window->RootWindowDockTree;
7540
0
  }
7541
0
    return window;
7542
0
}
7543
7544
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7545
0
{
7546
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7547
0
    if (window_root == potential_parent)
7548
0
        return true;
7549
0
    while (window != NULL)
7550
0
    {
7551
0
        if (window == potential_parent)
7552
0
            return true;
7553
0
        if (window == window_root) // end of chain
7554
0
            return false;
7555
0
        window = window->ParentWindow;
7556
0
    }
7557
0
    return false;
7558
0
}
7559
7560
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7561
0
{
7562
0
    if (window->RootWindow == potential_parent)
7563
0
        return true;
7564
0
    while (window != NULL)
7565
0
    {
7566
0
        if (window == potential_parent)
7567
0
            return true;
7568
0
        window = window->ParentWindowInBeginStack;
7569
0
    }
7570
0
    return false;
7571
0
}
7572
7573
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7574
0
{
7575
0
    ImGuiContext& g = *GImGui;
7576
7577
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7578
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7579
0
    if (display_layer_delta != 0)
7580
0
        return display_layer_delta > 0;
7581
7582
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7583
0
    {
7584
0
        ImGuiWindow* candidate_window = g.Windows[i];
7585
0
        if (candidate_window == potential_above)
7586
0
            return true;
7587
0
        if (candidate_window == potential_below)
7588
0
            return false;
7589
0
    }
7590
0
    return false;
7591
0
}
7592
7593
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7594
495
{
7595
495
    IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0);   // Flags not supported by this function
7596
495
    ImGuiContext& g = *GImGui;
7597
495
    ImGuiWindow* ref_window = g.HoveredWindow;
7598
495
    ImGuiWindow* cur_window = g.CurrentWindow;
7599
495
    if (ref_window == NULL)
7600
437
        return false;
7601
7602
58
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
7603
58
    {
7604
58
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
7605
58
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
7606
58
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
7607
58
        if (flags & ImGuiHoveredFlags_RootWindow)
7608
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7609
7610
58
        bool result;
7611
58
        if (flags & ImGuiHoveredFlags_ChildWindows)
7612
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7613
58
        else
7614
58
            result = (ref_window == cur_window);
7615
58
        if (!result)
7616
58
            return false;
7617
58
    }
7618
7619
0
    if (!IsWindowContentHoverable(ref_window, flags))
7620
0
        return false;
7621
0
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
7622
0
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
7623
0
            return false;
7624
0
    return true;
7625
0
}
7626
7627
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
7628
603
{
7629
603
    ImGuiContext& g = *GImGui;
7630
603
    ImGuiWindow* ref_window = g.NavWindow;
7631
603
    ImGuiWindow* cur_window = g.CurrentWindow;
7632
7633
603
    if (ref_window == NULL)
7634
142
        return false;
7635
461
    if (flags & ImGuiFocusedFlags_AnyWindow)
7636
0
        return true;
7637
7638
461
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
7639
461
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
7640
461
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
7641
461
    if (flags & ImGuiHoveredFlags_RootWindow)
7642
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7643
7644
461
    if (flags & ImGuiHoveredFlags_ChildWindows)
7645
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7646
461
    else
7647
461
        return (ref_window == cur_window);
7648
461
}
7649
7650
ImGuiID ImGui::GetWindowDockID()
7651
0
{
7652
0
    ImGuiContext& g = *GImGui;
7653
0
    return g.CurrentWindow->DockId;
7654
0
}
7655
7656
bool ImGui::IsWindowDocked()
7657
0
{
7658
0
    ImGuiContext& g = *GImGui;
7659
0
    return g.CurrentWindow->DockIsActive;
7660
0
}
7661
7662
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
7663
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
7664
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
7665
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
7666
0
{
7667
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
7668
0
}
7669
7670
float ImGui::GetWindowWidth()
7671
86
{
7672
86
    ImGuiWindow* window = GImGui->CurrentWindow;
7673
86
    return window->Size.x;
7674
86
}
7675
7676
float ImGui::GetWindowHeight()
7677
86
{
7678
86
    ImGuiWindow* window = GImGui->CurrentWindow;
7679
86
    return window->Size.y;
7680
86
}
7681
7682
ImVec2 ImGui::GetWindowPos()
7683
0
{
7684
0
    ImGuiContext& g = *GImGui;
7685
0
    ImGuiWindow* window = g.CurrentWindow;
7686
0
    return window->Pos;
7687
0
}
7688
7689
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
7690
22
{
7691
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7692
22
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
7693
0
        return;
7694
7695
22
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7696
22
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7697
22
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
7698
7699
    // Set
7700
22
    const ImVec2 old_pos = window->Pos;
7701
22
    window->Pos = ImFloor(pos);
7702
22
    ImVec2 offset = window->Pos - old_pos;
7703
22
    if (offset.x == 0.0f && offset.y == 0.0f)
7704
0
        return;
7705
22
    MarkIniSettingsDirty(window);
7706
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
7707
22
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
7708
22
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
7709
22
    window->DC.IdealMaxPos += offset;
7710
22
    window->DC.CursorStartPos += offset;
7711
22
}
7712
7713
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
7714
0
{
7715
0
    ImGuiWindow* window = GetCurrentWindowRead();
7716
0
    SetWindowPos(window, pos, cond);
7717
0
}
7718
7719
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
7720
0
{
7721
0
    if (ImGuiWindow* window = FindWindowByName(name))
7722
0
        SetWindowPos(window, pos, cond);
7723
0
}
7724
7725
ImVec2 ImGui::GetWindowSize()
7726
0
{
7727
0
    ImGuiWindow* window = GetCurrentWindowRead();
7728
0
    return window->Size;
7729
0
}
7730
7731
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
7732
90.5k
{
7733
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7734
90.5k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
7735
90.2k
        return;
7736
7737
312
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7738
312
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7739
7740
    // Set
7741
312
    ImVec2 old_size = window->SizeFull;
7742
312
    window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
7743
312
    window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
7744
312
    if (size.x <= 0.0f)
7745
0
        window->AutoFitOnlyGrows = false;
7746
312
    else
7747
312
        window->SizeFull.x = IM_FLOOR(size.x);
7748
312
    if (size.y <= 0.0f)
7749
0
        window->AutoFitOnlyGrows = false;
7750
312
    else
7751
312
        window->SizeFull.y = IM_FLOOR(size.y);
7752
312
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
7753
100
        MarkIniSettingsDirty(window);
7754
312
}
7755
7756
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
7757
0
{
7758
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
7759
0
}
7760
7761
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
7762
0
{
7763
0
    if (ImGuiWindow* window = FindWindowByName(name))
7764
0
        SetWindowSize(window, size, cond);
7765
0
}
7766
7767
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
7768
0
{
7769
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7770
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
7771
0
        return;
7772
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7773
7774
    // Set
7775
0
    window->Collapsed = collapsed;
7776
0
}
7777
7778
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
7779
0
{
7780
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
7781
0
    window->HitTestHoleSize = ImVec2ih(size);
7782
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
7783
0
}
7784
7785
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
7786
0
{
7787
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
7788
0
}
7789
7790
bool ImGui::IsWindowCollapsed()
7791
0
{
7792
0
    ImGuiWindow* window = GetCurrentWindowRead();
7793
0
    return window->Collapsed;
7794
0
}
7795
7796
bool ImGui::IsWindowAppearing()
7797
0
{
7798
0
    ImGuiWindow* window = GetCurrentWindowRead();
7799
0
    return window->Appearing;
7800
0
}
7801
7802
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
7803
0
{
7804
0
    if (ImGuiWindow* window = FindWindowByName(name))
7805
0
        SetWindowCollapsed(window, collapsed, cond);
7806
0
}
7807
7808
void ImGui::SetWindowFocus()
7809
86
{
7810
86
    FocusWindow(GImGui->CurrentWindow);
7811
86
}
7812
7813
void ImGui::SetWindowFocus(const char* name)
7814
0
{
7815
0
    if (name)
7816
0
    {
7817
0
        if (ImGuiWindow* window = FindWindowByName(name))
7818
0
            FocusWindow(window);
7819
0
    }
7820
0
    else
7821
0
    {
7822
0
        FocusWindow(NULL);
7823
0
    }
7824
0
}
7825
7826
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
7827
0
{
7828
0
    ImGuiContext& g = *GImGui;
7829
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7830
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
7831
0
    g.NextWindowData.PosVal = pos;
7832
0
    g.NextWindowData.PosPivotVal = pivot;
7833
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
7834
0
    g.NextWindowData.PosUndock = true;
7835
0
}
7836
7837
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
7838
90.5k
{
7839
90.5k
    ImGuiContext& g = *GImGui;
7840
90.5k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7841
90.5k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
7842
90.5k
    g.NextWindowData.SizeVal = size;
7843
90.5k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
7844
90.5k
}
7845
7846
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
7847
0
{
7848
0
    ImGuiContext& g = *GImGui;
7849
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
7850
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
7851
0
    g.NextWindowData.SizeCallback = custom_callback;
7852
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
7853
0
}
7854
7855
// Content size = inner scrollable rectangle, padded with WindowPadding.
7856
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
7857
void ImGui::SetNextWindowContentSize(const ImVec2& size)
7858
0
{
7859
0
    ImGuiContext& g = *GImGui;
7860
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
7861
0
    g.NextWindowData.ContentSizeVal = ImFloor(size);
7862
0
}
7863
7864
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
7865
0
{
7866
0
    ImGuiContext& g = *GImGui;
7867
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
7868
0
    g.NextWindowData.ScrollVal = scroll;
7869
0
}
7870
7871
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
7872
0
{
7873
0
    ImGuiContext& g = *GImGui;
7874
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7875
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
7876
0
    g.NextWindowData.CollapsedVal = collapsed;
7877
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
7878
0
}
7879
7880
void ImGui::SetNextWindowFocus()
7881
0
{
7882
0
    ImGuiContext& g = *GImGui;
7883
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
7884
0
}
7885
7886
void ImGui::SetNextWindowBgAlpha(float alpha)
7887
0
{
7888
0
    ImGuiContext& g = *GImGui;
7889
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
7890
0
    g.NextWindowData.BgAlphaVal = alpha;
7891
0
}
7892
7893
void ImGui::SetNextWindowViewport(ImGuiID id)
7894
0
{
7895
0
    ImGuiContext& g = *GImGui;
7896
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
7897
0
    g.NextWindowData.ViewportId = id;
7898
0
}
7899
7900
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
7901
0
{
7902
0
    ImGuiContext& g = *GImGui;
7903
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
7904
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
7905
0
    g.NextWindowData.DockId = id;
7906
0
}
7907
7908
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
7909
0
{
7910
0
    ImGuiContext& g = *GImGui;
7911
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
7912
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
7913
0
    g.NextWindowData.WindowClass = *window_class;
7914
0
}
7915
7916
ImDrawList* ImGui::GetWindowDrawList()
7917
311
{
7918
311
    ImGuiWindow* window = GetCurrentWindow();
7919
311
    return window->DrawList;
7920
311
}
7921
7922
float ImGui::GetWindowDpiScale()
7923
0
{
7924
0
    ImGuiContext& g = *GImGui;
7925
0
    return g.CurrentDpiScale;
7926
0
}
7927
7928
ImGuiViewport* ImGui::GetWindowViewport()
7929
0
{
7930
0
    ImGuiContext& g = *GImGui;
7931
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
7932
0
    return g.CurrentViewport;
7933
0
}
7934
7935
ImFont* ImGui::GetFont()
7936
3.25k
{
7937
3.25k
    return GImGui->Font;
7938
3.25k
}
7939
7940
float ImGui::GetFontSize()
7941
3.25k
{
7942
3.25k
    return GImGui->FontSize;
7943
3.25k
}
7944
7945
ImVec2 ImGui::GetFontTexUvWhitePixel()
7946
0
{
7947
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
7948
0
}
7949
7950
void ImGui::SetWindowFontScale(float scale)
7951
0
{
7952
0
    IM_ASSERT(scale > 0.0f);
7953
0
    ImGuiContext& g = *GImGui;
7954
0
    ImGuiWindow* window = GetCurrentWindow();
7955
0
    window->FontWindowScale = scale;
7956
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
7957
0
}
7958
7959
void ImGui::ActivateItem(ImGuiID id)
7960
0
{
7961
0
    ImGuiContext& g = *GImGui;
7962
0
    g.NavNextActivateId = id;
7963
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
7964
0
}
7965
7966
void ImGui::PushFocusScope(ImGuiID id)
7967
180k
{
7968
180k
    ImGuiContext& g = *GImGui;
7969
180k
    g.FocusScopeStack.push_back(id);
7970
180k
    g.CurrentFocusScopeId = id;
7971
180k
}
7972
7973
void ImGui::PopFocusScope()
7974
180k
{
7975
180k
    ImGuiContext& g = *GImGui;
7976
180k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
7977
180k
    g.FocusScopeStack.pop_back();
7978
180k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
7979
180k
}
7980
7981
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
7982
void ImGui::SetKeyboardFocusHere(int offset)
7983
0
{
7984
0
    ImGuiContext& g = *GImGui;
7985
0
    ImGuiWindow* window = g.CurrentWindow;
7986
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
7987
0
    IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
7988
7989
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
7990
    // When we refactor this function into ActivateItem() we may want to make this an option.
7991
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
7992
    // is also automatically dropped in the event g.ActiveId is stolen.
7993
0
    if (g.DragDropActive || g.MovingWindow != NULL)
7994
0
    {
7995
0
        IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere() ignored while DragDropActive!\n");
7996
0
        return;
7997
0
    }
7998
7999
0
    SetNavWindow(window);
8000
8001
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8002
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8003
0
    if (offset == -1)
8004
0
    {
8005
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8006
0
    }
8007
0
    else
8008
0
    {
8009
0
        g.NavTabbingDir = 1;
8010
0
        g.NavTabbingCounter = offset + 1;
8011
0
    }
8012
0
}
8013
8014
void ImGui::SetItemDefaultFocus()
8015
0
{
8016
0
    ImGuiContext& g = *GImGui;
8017
0
    ImGuiWindow* window = g.CurrentWindow;
8018
0
    if (!window->Appearing)
8019
0
        return;
8020
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8021
0
        return;
8022
8023
0
    g.NavInitRequest = false;
8024
0
    g.NavInitResultId = g.LastItemData.ID;
8025
0
    g.NavInitResultRectRel = WindowRectAbsToRel(window, g.LastItemData.Rect);
8026
0
    NavUpdateAnyRequestFlag();
8027
8028
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8029
0
    if (!IsItemVisible())
8030
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8031
0
}
8032
8033
void ImGui::SetStateStorage(ImGuiStorage* tree)
8034
0
{
8035
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8036
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8037
0
}
8038
8039
ImGuiStorage* ImGui::GetStateStorage()
8040
0
{
8041
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8042
0
    return window->DC.StateStorage;
8043
0
}
8044
8045
void ImGui::PushID(const char* str_id)
8046
309
{
8047
309
    ImGuiContext& g = *GImGui;
8048
309
    ImGuiWindow* window = g.CurrentWindow;
8049
309
    ImGuiID id = window->GetID(str_id);
8050
309
    window->IDStack.push_back(id);
8051
309
}
8052
8053
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8054
0
{
8055
0
    ImGuiContext& g = *GImGui;
8056
0
    ImGuiWindow* window = g.CurrentWindow;
8057
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8058
0
    window->IDStack.push_back(id);
8059
0
}
8060
8061
void ImGui::PushID(const void* ptr_id)
8062
0
{
8063
0
    ImGuiContext& g = *GImGui;
8064
0
    ImGuiWindow* window = g.CurrentWindow;
8065
0
    ImGuiID id = window->GetID(ptr_id);
8066
0
    window->IDStack.push_back(id);
8067
0
}
8068
8069
void ImGui::PushID(int int_id)
8070
0
{
8071
0
    ImGuiContext& g = *GImGui;
8072
0
    ImGuiWindow* window = g.CurrentWindow;
8073
0
    ImGuiID id = window->GetID(int_id);
8074
0
    window->IDStack.push_back(id);
8075
0
}
8076
8077
// Push a given id value ignoring the ID stack as a seed.
8078
void ImGui::PushOverrideID(ImGuiID id)
8079
0
{
8080
0
    ImGuiContext& g = *GImGui;
8081
0
    ImGuiWindow* window = g.CurrentWindow;
8082
0
    if (g.DebugHookIdInfo == id)
8083
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8084
0
    window->IDStack.push_back(id);
8085
0
}
8086
8087
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8088
// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
8089
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8090
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8091
0
{
8092
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8093
0
    ImGuiContext& g = *GImGui;
8094
0
    if (g.DebugHookIdInfo == id)
8095
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8096
0
    return id;
8097
0
}
8098
8099
void ImGui::PopID()
8100
309
{
8101
309
    ImGuiWindow* window = GImGui->CurrentWindow;
8102
309
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8103
309
    window->IDStack.pop_back();
8104
309
}
8105
8106
ImGuiID ImGui::GetID(const char* str_id)
8107
0
{
8108
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8109
0
    return window->GetID(str_id);
8110
0
}
8111
8112
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8113
0
{
8114
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8115
0
    return window->GetID(str_id_begin, str_id_end);
8116
0
}
8117
8118
ImGuiID ImGui::GetID(const void* ptr_id)
8119
0
{
8120
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8121
0
    return window->GetID(ptr_id);
8122
0
}
8123
8124
bool ImGui::IsRectVisible(const ImVec2& size)
8125
0
{
8126
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8127
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8128
0
}
8129
8130
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8131
0
{
8132
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8133
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8134
0
}
8135
8136
8137
//-----------------------------------------------------------------------------
8138
// [SECTION] INPUTS
8139
//-----------------------------------------------------------------------------
8140
// - GetKeyData() [Internal]
8141
// - GetKeyIndex() [Internal]
8142
// - GetKeyName()
8143
// - GetKeyChordName() [Internal]
8144
// - CalcTypematicRepeatAmount() [Internal]
8145
// - GetTypematicRepeatRate() [Internal]
8146
// - GetKeyPressedAmount() [Internal]
8147
// - GetKeyMagnitude2d() [Internal]
8148
//-----------------------------------------------------------------------------
8149
// - UpdateKeyRoutingTable() [Internal]
8150
// - GetRoutingIdFromOwnerId() [Internal]
8151
// - GetShortcutRoutingData() [Internal]
8152
// - CalcRoutingScore() [Internal]
8153
// - SetShortcutRouting() [Internal]
8154
// - TestShortcutRouting() [Internal]
8155
//-----------------------------------------------------------------------------
8156
// - IsKeyDown()
8157
// - IsKeyPressed()
8158
// - IsKeyReleased()
8159
//-----------------------------------------------------------------------------
8160
// - IsMouseDown()
8161
// - IsMouseClicked()
8162
// - IsMouseReleased()
8163
// - IsMouseDoubleClicked()
8164
// - GetMouseClickedCount()
8165
// - IsMouseHoveringRect() [Internal]
8166
// - IsMouseDragPastThreshold() [Internal]
8167
// - IsMouseDragging()
8168
// - GetMousePos()
8169
// - GetMousePosOnOpeningCurrentPopup()
8170
// - IsMousePosValid()
8171
// - IsAnyMouseDown()
8172
// - GetMouseDragDelta()
8173
// - ResetMouseDragDelta()
8174
// - GetMouseCursor()
8175
// - SetMouseCursor()
8176
//-----------------------------------------------------------------------------
8177
// - UpdateAliasKey()
8178
// - GetMergedModsFromKeys()
8179
// - UpdateKeyboardInputs()
8180
// - UpdateMouseInputs()
8181
//-----------------------------------------------------------------------------
8182
// - LockWheelingWindow [Internal]
8183
// - FindBestWheelingWindow [Internal]
8184
// - UpdateMouseWheel() [Internal]
8185
//-----------------------------------------------------------------------------
8186
// - SetNextFrameWantCaptureKeyboard()
8187
// - SetNextFrameWantCaptureMouse()
8188
//-----------------------------------------------------------------------------
8189
// - GetInputSourceName() [Internal]
8190
// - DebugPrintInputEvent() [Internal]
8191
// - UpdateInputEvents() [Internal]
8192
//-----------------------------------------------------------------------------
8193
// - GetKeyOwner() [Internal]
8194
// - TestKeyOwner() [Internal]
8195
// - SetKeyOwner() [Internal]
8196
// - SetItemKeyOwner() [Internal]
8197
// - Shortcut() [Internal]
8198
//-----------------------------------------------------------------------------
8199
8200
ImGuiKeyData* ImGui::GetKeyData(ImGuiKey key)
8201
2.17M
{
8202
2.17M
    ImGuiContext& g = *GImGui;
8203
8204
    // Special storage location for mods
8205
2.17M
    if (key & ImGuiMod_Mask_)
8206
811k
        key = ConvertSingleModFlagToKey(key);
8207
8208
2.17M
    int index;
8209
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8210
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8211
    if (IsLegacyKey(key))
8212
        index = (g.IO.KeyMap[key] != -1) ? g.IO.KeyMap[key] : key; // Remap native->imgui or imgui->native
8213
    else
8214
        index = key;
8215
#else
8216
2.17M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8217
2.17M
    index = key - ImGuiKey_NamedKey_BEGIN;
8218
2.17M
#endif
8219
2.17M
    return &g.IO.KeysData[index];
8220
2.17M
}
8221
8222
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8223
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8224
{
8225
    ImGuiContext& g = *GImGui;
8226
    IM_ASSERT(IsNamedKey(key));
8227
    const ImGuiKeyData* key_data = GetKeyData(key);
8228
    return (ImGuiKey)(key_data - g.IO.KeysData);
8229
}
8230
#endif
8231
8232
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8233
static const char* const GKeyNames[] =
8234
{
8235
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8236
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8237
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8238
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8239
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8240
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8241
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8242
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8243
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8244
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8245
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8246
    "GamepadStart", "GamepadBack",
8247
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8248
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8249
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8250
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8251
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8252
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8253
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8254
};
8255
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8256
8257
const char* ImGui::GetKeyName(ImGuiKey key)
8258
0
{
8259
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8260
0
    IM_ASSERT((IsNamedKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8261
#else
8262
    if (IsLegacyKey(key))
8263
    {
8264
        ImGuiIO& io = GetIO();
8265
        if (io.KeyMap[key] == -1)
8266
            return "N/A";
8267
        IM_ASSERT(IsNamedKey((ImGuiKey)io.KeyMap[key]));
8268
        key = (ImGuiKey)io.KeyMap[key];
8269
    }
8270
#endif
8271
0
    if (key == ImGuiKey_None)
8272
0
        return "None";
8273
0
    if (key & ImGuiMod_Mask_)
8274
0
        key = ConvertSingleModFlagToKey(key);
8275
0
    if (!IsNamedKey(key))
8276
0
        return "Unknown";
8277
8278
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8279
0
}
8280
8281
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8282
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8283
0
{
8284
0
    ImGuiContext& g = *GImGui;
8285
0
    if (key_chord & ImGuiMod_Shortcut)
8286
0
        key_chord = ConvertShortcutMod(key_chord);
8287
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8288
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8289
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8290
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8291
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8292
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8293
0
}
8294
8295
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8296
// t1 = current time (e.g.: g.Time)
8297
// An event is triggered at:
8298
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8299
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8300
20
{
8301
20
    if (t1 == 0.0f)
8302
0
        return 1;
8303
20
    if (t0 >= t1)
8304
0
        return 0;
8305
20
    if (repeat_rate <= 0.0f)
8306
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8307
20
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8308
20
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8309
20
    const int count = count_t1 - count_t0;
8310
20
    return count;
8311
20
}
8312
8313
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8314
199
{
8315
199
    ImGuiContext& g = *GImGui;
8316
199
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8317
199
    {
8318
73
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8319
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8320
126
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8321
199
    }
8322
199
}
8323
8324
// Return value representing the number of presses in the last time period, for the given repeat rate
8325
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8326
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8327
20
{
8328
20
    ImGuiContext& g = *GImGui;
8329
20
    const ImGuiKeyData* key_data = GetKeyData(key);
8330
20
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8331
0
        return 0;
8332
20
    const float t = key_data->DownDuration;
8333
20
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8334
20
}
8335
8336
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8337
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8338
0
{
8339
0
    return ImVec2(
8340
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8341
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8342
0
}
8343
8344
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8345
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8346
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8347
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8348
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8349
90.2k
{
8350
90.2k
    ImGuiContext& g = *GImGui;
8351
90.2k
    rt->EntriesNext.resize(0);
8352
12.7M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8353
12.6M
    {
8354
12.6M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8355
12.6M
        ImGuiKeyRoutingData* routing_entry;
8356
12.6M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8357
0
        {
8358
0
            routing_entry = &rt->Entries[old_routing_idx];
8359
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8360
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8361
0
            routing_entry->RoutingNextScore = 255;
8362
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8363
0
                continue;
8364
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8365
8366
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8367
0
            if (routing_entry->Mods == g.IO.KeyMods)
8368
0
            {
8369
0
                ImGuiKeyOwnerData* owner_data = ImGui::GetKeyOwnerData(key);
8370
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8371
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8372
0
            }
8373
0
        }
8374
8375
        // Rewrite linked-list
8376
12.6M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8377
12.6M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8378
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8379
12.6M
    }
8380
90.2k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8381
90.2k
}
8382
8383
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8384
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8385
0
{
8386
0
    ImGuiContext& g = *GImGui;
8387
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8388
0
}
8389
8390
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8391
0
{
8392
    // Majority of shortcuts will be Key + any number of Mods
8393
    // We accept _Single_ mod with ImGuiKey_None.
8394
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8395
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8396
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8397
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8398
0
    ImGuiContext& g = *GImGui;
8399
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8400
0
    ImGuiKeyRoutingData* routing_data;
8401
0
    if (key_chord & ImGuiMod_Shortcut)
8402
0
        key_chord = ConvertShortcutMod(key_chord);
8403
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8404
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8405
0
    if (key == ImGuiKey_None)
8406
0
        key = ConvertSingleModFlagToKey(mods);
8407
0
    IM_ASSERT(IsNamedKey(key));
8408
8409
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8410
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8411
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8412
0
    {
8413
0
        routing_data = &rt->Entries[idx];
8414
0
        if (routing_data->Mods == mods)
8415
0
            return routing_data;
8416
0
    }
8417
8418
    // Add to linked-list
8419
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8420
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8421
0
    routing_data = &rt->Entries[routing_data_idx];
8422
0
    routing_data->Mods = (ImU16)mods;
8423
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8424
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8425
0
    return routing_data;
8426
0
}
8427
8428
// Current score encoding (lower is highest priority):
8429
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8430
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8431
//  -   2: ImGuiInputFlags_RouteGlobal
8432
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8433
//  - 254: ImGuiInputFlags_RouteGlobalLow
8434
//  - 255: never route
8435
// 'flags' should include an explicit routing policy
8436
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8437
0
{
8438
0
    if (flags & ImGuiInputFlags_RouteFocused)
8439
0
    {
8440
0
        ImGuiContext& g = *GImGui;
8441
0
        ImGuiWindow* focused = g.NavWindow;
8442
8443
        // ActiveID gets top priority
8444
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8445
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8446
0
            return 1;
8447
8448
        // Score based on distance to focused window (lower is better)
8449
        // Assuming both windows are submitting a routing request,
8450
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8451
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8452
        // Assuming only WindowA is submitting a routing request,
8453
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8454
0
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8455
0
            for (int next_score = 3; focused != NULL; next_score++)
8456
0
            {
8457
0
                if (focused == location)
8458
0
                {
8459
0
                    IM_ASSERT(next_score < 255);
8460
0
                    return next_score;
8461
0
                }
8462
0
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8463
0
            }
8464
0
        return 255;
8465
0
    }
8466
8467
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8468
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8469
0
        return 2;
8470
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8471
0
        return 254;
8472
0
    return 0;
8473
0
}
8474
8475
// Request a desired route for an input chord (key + mods).
8476
// Return true if the route is available this frame.
8477
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8478
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8479
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8480
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8481
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8482
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8483
180k
{
8484
180k
    ImGuiContext& g = *GImGui;
8485
180k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8486
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8487
180k
    else
8488
180k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8489
8490
180k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8491
0
        if (g.NavWindow == NULL)
8492
0
            return false;
8493
180k
    if (flags & ImGuiInputFlags_RouteAlways)
8494
180k
        return true;
8495
8496
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8497
0
    if (score == 255)
8498
0
        return false;
8499
8500
    // Submit routing for NEXT frame (assuming score is sufficient)
8501
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8502
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8503
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8504
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8505
0
    if (score < routing_data->RoutingNextScore)
8506
0
    {
8507
0
        routing_data->RoutingNext = routing_id;
8508
0
        routing_data->RoutingNextScore = (ImU8)score;
8509
0
    }
8510
8511
    // Return routing state for CURRENT frame
8512
0
    return routing_data->RoutingCurr == routing_id;
8513
0
}
8514
8515
// Currently unused by core (but used by tests)
8516
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8517
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8518
0
{
8519
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8520
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8521
0
    return routing_data->RoutingCurr == routing_id;
8522
0
}
8523
8524
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8525
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8526
bool ImGui::IsKeyDown(ImGuiKey key)
8527
1.35M
{
8528
1.35M
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8529
1.35M
}
8530
8531
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8532
1.35M
{
8533
1.35M
    const ImGuiKeyData* key_data = GetKeyData(key);
8534
1.35M
    if (!key_data->Down)
8535
1.32M
        return false;
8536
26.1k
    if (!TestKeyOwner(key, owner_id))
8537
10
        return false;
8538
26.0k
    return true;
8539
26.1k
}
8540
8541
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8542
2.46k
{
8543
2.46k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8544
2.46k
}
8545
8546
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8547
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
8548
185k
{
8549
185k
    const ImGuiKeyData* key_data = GetKeyData(key);
8550
185k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8551
179k
        return false;
8552
5.14k
    const float t = key_data->DownDuration;
8553
5.14k
    if (t < 0.0f)
8554
0
        return false;
8555
5.14k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8556
8557
5.14k
    bool pressed = (t == 0.0f);
8558
5.14k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
8559
199
    {
8560
199
        float repeat_delay, repeat_rate;
8561
199
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
8562
199
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
8563
199
    }
8564
5.14k
    if (!pressed)
8565
4.58k
        return false;
8566
563
    if (!TestKeyOwner(key, owner_id))
8567
0
        return false;
8568
563
    return true;
8569
563
}
8570
8571
bool ImGui::IsKeyReleased(ImGuiKey key)
8572
0
{
8573
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
8574
0
}
8575
8576
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
8577
0
{
8578
0
    const ImGuiKeyData* key_data = GetKeyData(key);
8579
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
8580
0
        return false;
8581
0
    if (!TestKeyOwner(key, owner_id))
8582
0
        return false;
8583
0
    return true;
8584
0
}
8585
8586
bool ImGui::IsMouseDown(ImGuiMouseButton button)
8587
0
{
8588
0
    ImGuiContext& g = *GImGui;
8589
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8590
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
8591
0
}
8592
8593
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
8594
114
{
8595
114
    ImGuiContext& g = *GImGui;
8596
114
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8597
114
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
8598
114
}
8599
8600
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
8601
6
{
8602
6
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8603
6
}
8604
8605
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
8606
340
{
8607
340
    ImGuiContext& g = *GImGui;
8608
340
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8609
340
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8610
232
        return false;
8611
108
    const float t = g.IO.MouseDownDuration[button];
8612
108
    if (t < 0.0f)
8613
0
        return false;
8614
108
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8615
8616
108
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
8617
108
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
8618
108
    if (!pressed)
8619
81
        return false;
8620
8621
27
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
8622
0
        return false;
8623
8624
27
    return true;
8625
27
}
8626
8627
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
8628
0
{
8629
0
    ImGuiContext& g = *GImGui;
8630
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8631
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
8632
0
}
8633
8634
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
8635
334
{
8636
334
    ImGuiContext& g = *GImGui;
8637
334
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8638
334
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
8639
334
}
8640
8641
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
8642
0
{
8643
0
    ImGuiContext& g = *GImGui;
8644
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8645
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
8646
0
}
8647
8648
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
8649
0
{
8650
0
    ImGuiContext& g = *GImGui;
8651
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8652
0
    return g.IO.MouseClickedCount[button];
8653
0
}
8654
8655
// Test if mouse cursor is hovering given rectangle
8656
// NB- Rectangle is clipped by our current clip setting
8657
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
8658
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
8659
362k
{
8660
362k
    ImGuiContext& g = *GImGui;
8661
8662
    // Clip
8663
362k
    ImRect rect_clipped(r_min, r_max);
8664
362k
    if (clip)
8665
182k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
8666
8667
    // Expand for touch input
8668
362k
    const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
8669
362k
    if (!rect_for_touch.Contains(g.IO.MousePos))
8670
352k
        return false;
8671
10.4k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
8672
0
        return false;
8673
10.4k
    return true;
8674
10.4k
}
8675
8676
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
8677
// [Internal] This doesn't test if the button is pressed
8678
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
8679
156
{
8680
156
    ImGuiContext& g = *GImGui;
8681
156
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8682
156
    if (lock_threshold < 0.0f)
8683
150
        lock_threshold = g.IO.MouseDragThreshold;
8684
156
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
8685
156
}
8686
8687
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
8688
156
{
8689
156
    ImGuiContext& g = *GImGui;
8690
156
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8691
156
    if (!g.IO.MouseDown[button])
8692
0
        return false;
8693
156
    return IsMouseDragPastThreshold(button, lock_threshold);
8694
156
}
8695
8696
ImVec2 ImGui::GetMousePos()
8697
87
{
8698
87
    ImGuiContext& g = *GImGui;
8699
87
    return g.IO.MousePos;
8700
87
}
8701
8702
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
8703
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
8704
0
{
8705
0
    ImGuiContext& g = *GImGui;
8706
0
    if (g.BeginPopupStack.Size > 0)
8707
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
8708
0
    return g.IO.MousePos;
8709
0
}
8710
8711
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
8712
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
8713
260k
{
8714
    // The assert is only to silence a false-positive in XCode Static Analysis.
8715
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
8716
260k
    IM_ASSERT(GImGui != NULL);
8717
260k
    const float MOUSE_INVALID = -256000.0f;
8718
260k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
8719
260k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
8720
260k
}
8721
8722
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
8723
bool ImGui::IsAnyMouseDown()
8724
0
{
8725
0
    ImGuiContext& g = *GImGui;
8726
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
8727
0
        if (g.IO.MouseDown[n])
8728
0
            return true;
8729
0
    return false;
8730
0
}
8731
8732
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
8733
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
8734
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
8735
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
8736
0
{
8737
0
    ImGuiContext& g = *GImGui;
8738
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8739
0
    if (lock_threshold < 0.0f)
8740
0
        lock_threshold = g.IO.MouseDragThreshold;
8741
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
8742
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
8743
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
8744
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
8745
0
    return ImVec2(0.0f, 0.0f);
8746
0
}
8747
8748
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
8749
0
{
8750
0
    ImGuiContext& g = *GImGui;
8751
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8752
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
8753
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
8754
0
}
8755
8756
// Get desired mouse cursor shape.
8757
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
8758
// updated during the frame, and locked in EndFrame()/Render().
8759
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
8760
ImGuiMouseCursor ImGui::GetMouseCursor()
8761
0
{
8762
0
    ImGuiContext& g = *GImGui;
8763
0
    return g.MouseCursor;
8764
0
}
8765
8766
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
8767
0
{
8768
0
    ImGuiContext& g = *GImGui;
8769
0
    g.MouseCursor = cursor_type;
8770
0
}
8771
8772
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
8773
631k
{
8774
631k
    IM_ASSERT(ImGui::IsAliasKey(key));
8775
631k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
8776
631k
    key_data->Down = v;
8777
631k
    key_data->AnalogValue = analog_value;
8778
631k
}
8779
8780
// [Internal] Do not use directly
8781
static ImGuiKeyChord GetMergedModsFromKeys()
8782
180k
{
8783
180k
    ImGuiKeyChord mods = 0;
8784
180k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
8785
180k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
8786
180k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
8787
180k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
8788
180k
    return mods;
8789
180k
}
8790
8791
static void ImGui::UpdateKeyboardInputs()
8792
90.2k
{
8793
90.2k
    ImGuiContext& g = *GImGui;
8794
90.2k
    ImGuiIO& io = g.IO;
8795
8796
    // Import legacy keys or verify they are not used
8797
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8798
    if (io.BackendUsingLegacyKeyArrays == 0)
8799
    {
8800
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
8801
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
8802
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
8803
    }
8804
    else
8805
    {
8806
        if (g.FrameCount == 0)
8807
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
8808
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
8809
8810
        // Build reverse KeyMap (Named -> Legacy)
8811
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
8812
            if (io.KeyMap[n] != -1)
8813
            {
8814
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
8815
                io.KeyMap[io.KeyMap[n]] = n;
8816
            }
8817
8818
        // Import legacy keys into new ones
8819
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
8820
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
8821
            {
8822
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
8823
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
8824
                io.KeysData[key].Down = io.KeysDown[n];
8825
                if (key != n)
8826
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
8827
                io.BackendUsingLegacyKeyArrays = 1;
8828
            }
8829
        if (io.BackendUsingLegacyKeyArrays == 1)
8830
        {
8831
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
8832
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
8833
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
8834
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
8835
        }
8836
    }
8837
8838
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8839
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
8840
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
8841
    {
8842
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
8843
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
8844
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
8845
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
8846
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
8847
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
8848
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
8849
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
8850
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
8851
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
8852
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
8853
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
8854
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
8855
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
8856
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
8857
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
8858
        #undef NAV_MAP_KEY
8859
    }
8860
#endif
8861
#endif
8862
8863
    // Update aliases
8864
541k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
8865
451k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
8866
90.2k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
8867
90.2k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
8868
8869
    // Synchronize io.KeyMods and io.KeyXXX values.
8870
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
8871
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
8872
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
8873
90.2k
    io.KeyMods = GetMergedModsFromKeys();
8874
90.2k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
8875
90.2k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
8876
90.2k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
8877
90.2k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
8878
8879
    // Clear gamepad data if disabled
8880
90.2k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
8881
2.25M
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
8882
2.16M
        {
8883
2.16M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
8884
2.16M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
8885
2.16M
        }
8886
8887
    // Update keys
8888
12.7M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
8889
12.6M
    {
8890
12.6M
        ImGuiKeyData* key_data = &io.KeysData[i];
8891
12.6M
        key_data->DownDurationPrev = key_data->DownDuration;
8892
12.6M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
8893
12.6M
    }
8894
8895
    // Update keys/input owner (named keys only): one entry per key
8896
12.7M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8897
12.6M
    {
8898
12.6M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
8899
12.6M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
8900
12.6M
        owner_data->OwnerCurr = owner_data->OwnerNext;
8901
12.6M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
8902
12.5M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
8903
12.6M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
8904
12.6M
    }
8905
8906
90.2k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
8907
90.2k
}
8908
8909
static void ImGui::UpdateMouseInputs()
8910
90.2k
{
8911
90.2k
    ImGuiContext& g = *GImGui;
8912
90.2k
    ImGuiIO& io = g.IO;
8913
8914
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
8915
90.2k
    if (IsMousePosValid(&io.MousePos))
8916
33.4k
        io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos);
8917
8918
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
8919
90.2k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
8920
32.1k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
8921
58.0k
    else
8922
58.0k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
8923
8924
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
8925
90.2k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
8926
1.69k
        g.NavDisableMouseHover = false;
8927
8928
90.2k
    io.MousePosPrev = io.MousePos;
8929
541k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
8930
451k
    {
8931
451k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
8932
451k
        io.MouseClickedCount[i] = 0; // Will be filled below
8933
451k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
8934
451k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
8935
451k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
8936
451k
        if (io.MouseClicked[i])
8937
6.99k
        {
8938
6.99k
            bool is_repeated_click = false;
8939
6.99k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
8940
4.78k
            {
8941
4.78k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
8942
4.78k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
8943
4.45k
                    is_repeated_click = true;
8944
4.78k
            }
8945
6.99k
            if (is_repeated_click)
8946
4.45k
                io.MouseClickedLastCount[i]++;
8947
2.54k
            else
8948
2.54k
                io.MouseClickedLastCount[i] = 1;
8949
6.99k
            io.MouseClickedTime[i] = g.Time;
8950
6.99k
            io.MouseClickedPos[i] = io.MousePos;
8951
6.99k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
8952
6.99k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
8953
6.99k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
8954
6.99k
        }
8955
444k
        else if (io.MouseDown[i])
8956
41.1k
        {
8957
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
8958
41.1k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
8959
41.1k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
8960
41.1k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
8961
41.1k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
8962
41.1k
        }
8963
8964
        // We provide io.MouseDoubleClicked[] as a legacy service
8965
451k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
8966
8967
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
8968
451k
        if (io.MouseClicked[i])
8969
6.99k
            g.NavDisableMouseHover = false;
8970
451k
    }
8971
90.2k
}
8972
8973
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
8974
0
{
8975
0
    ImGuiContext& g = *GImGui;
8976
0
    if (window)
8977
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
8978
0
    else
8979
0
        g.WheelingWindowReleaseTimer = 0.0f;
8980
0
    if (g.WheelingWindow == window)
8981
0
        return;
8982
0
    IMGUI_DEBUG_LOG_IO("LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
8983
0
    g.WheelingWindow = window;
8984
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
8985
0
    if (window == NULL)
8986
0
    {
8987
0
        g.WheelingWindowStartFrame = -1;
8988
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
8989
0
    }
8990
0
}
8991
8992
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
8993
0
{
8994
    // For each axis, find window in the hierarchy that may want to use scrolling
8995
0
    ImGuiContext& g = *GImGui;
8996
0
    ImGuiWindow* windows[2] = { NULL, NULL };
8997
0
    for (int axis = 0; axis < 2; axis++)
8998
0
        if (wheel[axis] != 0.0f)
8999
0
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9000
0
            {
9001
                // Bubble up into parent window if:
9002
                // - a child window doesn't allow any scrolling.
9003
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9004
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9005
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9006
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9007
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9008
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9009
0
                    break; // select this window
9010
0
            }
9011
0
    if (windows[0] == NULL && windows[1] == NULL)
9012
0
        return NULL;
9013
9014
    // If there's only one window or only one axis then there's no ambiguity
9015
0
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9016
0
        return windows[1] ? windows[1] : windows[0];
9017
9018
    // If candidate are different windows we need to decide which one to prioritize
9019
    // - First frame: only find a winner if one axis is zero.
9020
    // - Subsequent frames: only find a winner when one is more than the other.
9021
0
    if (g.WheelingWindowStartFrame == -1)
9022
0
        g.WheelingWindowStartFrame = g.FrameCount;
9023
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9024
0
    {
9025
0
        g.WheelingWindowWheelRemainder = wheel;
9026
0
        return NULL;
9027
0
    }
9028
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9029
0
}
9030
9031
// Called by NewFrame()
9032
void ImGui::UpdateMouseWheel()
9033
90.2k
{
9034
    // Reset the locked window if we move the mouse or after the timer elapses.
9035
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9036
90.2k
    ImGuiContext& g = *GImGui;
9037
90.2k
    if (g.WheelingWindow != NULL)
9038
0
    {
9039
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9040
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9041
0
            g.WheelingWindowReleaseTimer = 0.0f;
9042
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9043
0
            LockWheelingWindow(NULL, 0.0f);
9044
0
    }
9045
9046
90.2k
    ImVec2 wheel;
9047
90.2k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9048
90.2k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9049
9050
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9051
90.2k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9052
90.2k
    if (!mouse_window || mouse_window->Collapsed)
9053
90.1k
        return;
9054
9055
    // Zoom / Scale window
9056
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9057
46
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9058
0
    {
9059
0
        LockWheelingWindow(mouse_window, wheel.y);
9060
0
        ImGuiWindow* window = mouse_window;
9061
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9062
0
        const float scale = new_font_scale / window->FontWindowScale;
9063
0
        window->FontWindowScale = new_font_scale;
9064
0
        if (window == window->RootWindow)
9065
0
        {
9066
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9067
0
            SetWindowPos(window, window->Pos + offset, 0);
9068
0
            window->Size = ImFloor(window->Size * scale);
9069
0
            window->SizeFull = ImFloor(window->SizeFull * scale);
9070
0
        }
9071
0
        return;
9072
0
    }
9073
46
    if (g.IO.KeyCtrl)
9074
0
        return;
9075
9076
    // Mouse wheel scrolling
9077
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9078
    // (we avoid doing it on OSX as it the OS input layer handles this already)
9079
46
    const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors;
9080
46
    if (swap_axis)
9081
0
    {
9082
0
        wheel.x = wheel.y;
9083
0
        wheel.y = 0.0f;
9084
0
    }
9085
9086
    // Maintain a rough average of moving magnitude on both axises
9087
    // FIXME: should by based on wall clock time rather than frame-counter
9088
46
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9089
46
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9090
9091
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9092
46
    wheel += g.WheelingWindowWheelRemainder;
9093
46
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9094
46
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9095
46
        return;
9096
9097
    // Mouse wheel scrolling: find target and apply
9098
    // - don't renew lock if axis doesn't apply on the window.
9099
    // - select a main axis when both axises are being moved.
9100
0
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9101
0
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9102
0
        {
9103
0
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9104
0
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9105
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9106
0
            if (do_scroll[ImGuiAxis_X])
9107
0
            {
9108
0
                LockWheelingWindow(window, wheel.x);
9109
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9110
0
                float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
9111
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9112
0
            }
9113
0
            if (do_scroll[ImGuiAxis_Y])
9114
0
            {
9115
0
                LockWheelingWindow(window, wheel.y);
9116
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9117
0
                float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
9118
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9119
0
            }
9120
0
        }
9121
0
}
9122
9123
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9124
0
{
9125
0
    ImGuiContext& g = *GImGui;
9126
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9127
0
}
9128
9129
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9130
0
{
9131
0
    ImGuiContext& g = *GImGui;
9132
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9133
0
}
9134
9135
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9136
static const char* GetInputSourceName(ImGuiInputSource source)
9137
0
{
9138
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Nav", "Clipboard" };
9139
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9140
0
    return input_source_names[source];
9141
0
}
9142
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9143
0
{
9144
0
    ImGuiContext& g = *GImGui;
9145
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("%s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("%s: MousePos (%.1f, %.1f)\n", prefix, e->MousePos.PosX, e->MousePos.PosY); return; }
9146
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("%s: MouseButton %d %s\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up"); return; }
9147
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("%s: MouseWheel (%.3f, %.3f)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY); return; }
9148
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("%s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9149
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("%s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9150
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("%s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9151
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("%s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9152
0
}
9153
#endif
9154
9155
// Process input queue
9156
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9157
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9158
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9159
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9160
90.2k
{
9161
90.2k
    ImGuiContext& g = *GImGui;
9162
90.2k
    ImGuiIO& io = g.IO;
9163
9164
    // Only trickle chars<>key when working with InputText()
9165
    // FIXME: InputText() could parse event trail?
9166
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9167
90.2k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9168
9169
90.2k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9170
90.2k
    int  mouse_button_changed = 0x00;
9171
90.2k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9172
9173
90.2k
    int event_n = 0;
9174
124k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9175
41.2k
    {
9176
41.2k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9177
41.2k
        if (e->Type == ImGuiInputEventType_MousePos)
9178
5.77k
        {
9179
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9180
5.77k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9181
5.77k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9182
1.22k
                break;
9183
4.55k
            io.MousePos = event_pos;
9184
4.55k
            mouse_moved = true;
9185
4.55k
        }
9186
35.4k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9187
12.3k
        {
9188
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9189
12.3k
            const ImGuiMouseButton button = e->MouseButton.Button;
9190
12.3k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9191
12.3k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9192
2.38k
                break;
9193
9.99k
            io.MouseDown[button] = e->MouseButton.Down;
9194
9.99k
            mouse_button_changed |= (1 << button);
9195
9.99k
        }
9196
23.0k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9197
5.69k
        {
9198
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9199
5.69k
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9200
2.17k
                break;
9201
3.52k
            io.MouseWheelH += e->MouseWheel.WheelX;
9202
3.52k
            io.MouseWheel += e->MouseWheel.WheelY;
9203
3.52k
            mouse_wheeled = true;
9204
3.52k
        }
9205
17.3k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9206
0
        {
9207
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9208
0
        }
9209
17.3k
        else if (e->Type == ImGuiInputEventType_Key)
9210
3.21k
        {
9211
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9212
3.21k
            ImGuiKey key = e->Key.Key;
9213
3.21k
            IM_ASSERT(key != ImGuiKey_None);
9214
3.21k
            ImGuiKeyData* key_data = GetKeyData(key);
9215
3.21k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9216
3.21k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9217
88
                break;
9218
3.12k
            key_data->Down = e->Key.Down;
9219
3.12k
            key_data->AnalogValue = e->Key.AnalogValue;
9220
3.12k
            key_changed = true;
9221
3.12k
            key_changed_mask.SetBit(key_data_index);
9222
9223
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9224
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9225
            io.KeysDown[key_data_index] = key_data->Down;
9226
            if (io.KeyMap[key_data_index] != -1)
9227
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9228
#endif
9229
3.12k
        }
9230
14.1k
        else if (e->Type == ImGuiInputEventType_Text)
9231
8.67k
        {
9232
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9233
8.67k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9234
1.15k
                break;
9235
7.52k
            unsigned int c = e->Text.Char;
9236
7.52k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9237
7.52k
            if (trickle_interleaved_keys_and_text)
9238
0
                text_inputted = true;
9239
7.52k
        }
9240
5.49k
        else if (e->Type == ImGuiInputEventType_Focus)
9241
5.49k
        {
9242
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9243
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9244
5.49k
            const bool focus_lost = !e->AppFocused.Focused;
9245
5.49k
            io.AppFocusLost = focus_lost;
9246
5.49k
        }
9247
0
        else
9248
0
        {
9249
0
            IM_ASSERT(0 && "Unknown event!");
9250
0
        }
9251
41.2k
    }
9252
9253
    // Record trail (for domain-specific applications wanting to access a precise trail)
9254
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9255
124k
    for (int n = 0; n < event_n; n++)
9256
34.2k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9257
9258
    // [DEBUG]
9259
90.2k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9260
90.2k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9261
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9262
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9263
90.2k
#endif
9264
9265
    // Remaining events will be processed on the next frame
9266
90.2k
    if (event_n == g.InputEventsQueue.Size)
9267
83.1k
        g.InputEventsQueue.resize(0);
9268
7.02k
    else
9269
7.02k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9270
9271
    // Clear buttons state when focus is lost
9272
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9273
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9274
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9275
90.2k
    if (g.IO.AppFocusLost)
9276
4.39k
        g.IO.ClearInputKeys();
9277
90.2k
}
9278
9279
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9280
0
{
9281
0
    if (!IsNamedKeyOrModKey(key))
9282
0
        return ImGuiKeyOwner_None;
9283
9284
0
    ImGuiContext& g = *GImGui;
9285
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9286
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9287
9288
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9289
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9290
0
            return ImGuiKeyOwner_None;
9291
9292
0
    return owner_id;
9293
0
}
9294
9295
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9296
// TestKeyOwner(..., None) : (owner == None)
9297
// TestKeyOwner(..., Any)  : no owner test
9298
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9299
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9300
207k
{
9301
207k
    if (!IsNamedKeyOrModKey(key))
9302
0
        return true;
9303
9304
207k
    ImGuiContext& g = *GImGui;
9305
207k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9306
116
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9307
10
            return false;
9308
9309
207k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9310
207k
    if (owner_id == ImGuiKeyOwner_Any)
9311
26.0k
        return (owner_data->LockThisFrame == false);
9312
9313
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9314
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9315
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9316
181k
    if (owner_data->OwnerCurr != owner_id)
9317
28
    {
9318
28
        if (owner_data->LockThisFrame)
9319
0
            return false;
9320
28
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9321
0
            return false;
9322
28
    }
9323
9324
181k
    return true;
9325
181k
}
9326
9327
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9328
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9329
// - SetKeyOwner(..., None)              : clears owner
9330
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9331
// - SetKeyOwner(..., Any or None, Lock) : set lock
9332
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9333
27
{
9334
27
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9335
27
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9336
9337
27
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9338
27
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9339
9340
    // We cannot lock by default as it would likely break lots of legacy code.
9341
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9342
27
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9343
27
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9344
27
}
9345
9346
// This is more or less equivalent to:
9347
//   if (IsItemHovered() || IsItemActive())
9348
//       SetKeyOwner(key, GetItemID());
9349
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9350
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9351
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9352
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9353
0
{
9354
0
    ImGuiContext& g = *GImGui;
9355
0
    ImGuiID id = g.LastItemData.ID;
9356
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9357
0
        return;
9358
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9359
0
        flags |= ImGuiInputFlags_CondDefault_;
9360
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9361
0
    {
9362
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9363
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9364
0
    }
9365
0
}
9366
9367
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9368
180k
{
9369
180k
    ImGuiContext& g = *GImGui;
9370
9371
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9372
180k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9373
180k
        flags |= ImGuiInputFlags_RouteFocused;
9374
180k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9375
0
        return false;
9376
9377
180k
    if (key_chord & ImGuiMod_Shortcut)
9378
0
        key_chord = ConvertShortcutMod(key_chord);
9379
180k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9380
180k
    if (g.IO.KeyMods != mods)
9381
180k
        return false;
9382
9383
    // Special storage location for mods
9384
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9385
0
    if (key == ImGuiKey_None)
9386
0
        key = ConvertSingleModFlagToKey(mods);
9387
9388
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9389
0
        return false;
9390
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9391
9392
0
    return true;
9393
0
}
9394
9395
9396
//-----------------------------------------------------------------------------
9397
// [SECTION] ERROR CHECKING
9398
//-----------------------------------------------------------------------------
9399
9400
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9401
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9402
// If this triggers you have an issue:
9403
// - Most commonly: mismatched headers and compiled code version.
9404
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9405
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9406
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9407
//   Otherwise it is possible that different compilation units would see different structure layout
9408
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9409
1
{
9410
1
    bool error = false;
9411
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9412
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9413
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9414
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9415
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9416
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9417
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9418
1
    return !error;
9419
1
}
9420
9421
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9422
// This is causing issues and ambiguity and we need to retire that.
9423
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9424
// [Scenario 1]
9425
//  Previously this would make the window content size ~200x200:
9426
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9427
//  Instead, please submit an item:
9428
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9429
//  Alternative:
9430
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9431
// [Scenario 2]
9432
//  For reference this is one of the issue what we aim to fix with this change:
9433
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9434
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9435
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9436
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9437
0
{
9438
0
    ImGuiContext& g = *GImGui;
9439
0
    ImGuiWindow* window = g.CurrentWindow;
9440
0
    IM_ASSERT(window->DC.IsSetPos);
9441
0
    window->DC.IsSetPos = false;
9442
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9443
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9444
0
        return;
9445
0
    if (window->SkipItems)
9446
0
        return;
9447
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9448
#else
9449
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9450
#endif
9451
0
}
9452
9453
static void ImGui::ErrorCheckNewFrameSanityChecks()
9454
90.2k
{
9455
90.2k
    ImGuiContext& g = *GImGui;
9456
9457
    // Check user IM_ASSERT macro
9458
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9459
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9460
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9461
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9462
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9463
90.2k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9464
9465
    // Check user data
9466
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9467
90.2k
    IM_ASSERT(g.Initialized);
9468
90.2k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9469
90.2k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9470
90.2k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9471
90.2k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9472
90.2k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9473
90.2k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
9474
90.2k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
9475
90.2k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
9476
90.2k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
9477
90.2k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
9478
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9479
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
9480
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
9481
9482
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
9483
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
9484
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
9485
#endif
9486
9487
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
9488
90.2k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
9489
1
        g.IO.ConfigWindowsResizeFromEdges = false;
9490
9491
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
9492
90.2k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
9493
90.2k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9494
90.2k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
9495
90.2k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9496
9497
    // Perform simple checks: multi-viewport and platform windows support
9498
90.2k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
9499
1
    {
9500
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
9501
0
        {
9502
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
9503
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
9504
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
9505
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
9506
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
9507
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
9508
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
9509
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
9510
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
9511
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
9512
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
9513
0
        }
9514
1
        else
9515
1
        {
9516
            // Disable feature, our backends do not support it
9517
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
9518
1
        }
9519
9520
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
9521
1
        for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
9522
0
        {
9523
0
            ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
9524
0
            IM_UNUSED(mon);
9525
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
9526
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
9527
0
            IM_ASSERT(mon.DpiScale != 0.0f);
9528
0
        }
9529
1
    }
9530
90.2k
}
9531
9532
static void ImGui::ErrorCheckEndFrameSanityChecks()
9533
90.2k
{
9534
90.2k
    ImGuiContext& g = *GImGui;
9535
9536
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
9537
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
9538
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
9539
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
9540
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
9541
    // while still correctly asserting on mid-frame key press events.
9542
90.2k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
9543
90.2k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
9544
90.2k
    IM_UNUSED(key_mods);
9545
9546
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
9547
    //ErrorCheckEndFrameRecover();
9548
9549
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
9550
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
9551
90.2k
    if (g.CurrentWindowStack.Size != 1)
9552
0
    {
9553
0
        if (g.CurrentWindowStack.Size > 1)
9554
0
        {
9555
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
9556
0
            while (g.CurrentWindowStack.Size > 1)
9557
0
                End();
9558
0
        }
9559
0
        else
9560
0
        {
9561
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
9562
0
        }
9563
0
    }
9564
9565
90.2k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
9566
90.2k
}
9567
9568
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
9569
// Must be called during or before EndFrame().
9570
// This is generally flawed as we are not necessarily End/Popping things in the right order.
9571
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
9572
// FIXME: Can't recover from interleaved BeginTabBar/Begin
9573
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9574
0
{
9575
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
9576
0
    ImGuiContext& g = *GImGui;
9577
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
9578
0
    {
9579
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
9580
0
        ImGuiWindow* window = g.CurrentWindow;
9581
0
        if (g.CurrentWindowStack.Size == 1)
9582
0
        {
9583
0
            IM_ASSERT(window->IsFallbackWindow);
9584
0
            break;
9585
0
        }
9586
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
9587
0
        {
9588
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
9589
0
            EndChild();
9590
0
        }
9591
0
        else
9592
0
        {
9593
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
9594
0
            End();
9595
0
        }
9596
0
    }
9597
0
}
9598
9599
// Must be called before End()/EndChild()
9600
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9601
0
{
9602
0
    ImGuiContext& g = *GImGui;
9603
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
9604
0
    {
9605
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
9606
0
        EndTable();
9607
0
    }
9608
9609
0
    ImGuiWindow* window = g.CurrentWindow;
9610
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
9611
0
    IM_ASSERT(window != NULL);
9612
0
    while (g.CurrentTabBar != NULL) //-V1044
9613
0
    {
9614
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
9615
0
        EndTabBar();
9616
0
    }
9617
0
    while (window->DC.TreeDepth > 0)
9618
0
    {
9619
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
9620
0
        TreePop();
9621
0
    }
9622
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
9623
0
    {
9624
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
9625
0
        EndGroup();
9626
0
    }
9627
0
    while (window->IDStack.Size > 1)
9628
0
    {
9629
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
9630
0
        PopID();
9631
0
    }
9632
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
9633
0
    {
9634
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
9635
0
        EndDisabled();
9636
0
    }
9637
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
9638
0
    {
9639
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
9640
0
        PopStyleColor();
9641
0
    }
9642
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
9643
0
    {
9644
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
9645
0
        PopItemFlag();
9646
0
    }
9647
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
9648
0
    {
9649
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
9650
0
        PopStyleVar();
9651
0
    }
9652
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
9653
0
    {
9654
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
9655
0
        PopFocusScope();
9656
0
    }
9657
0
}
9658
9659
// Save current stack sizes for later compare
9660
void ImGuiStackSizes::SetToCurrentState()
9661
180k
{
9662
180k
    ImGuiContext& g = *GImGui;
9663
180k
    ImGuiWindow* window = g.CurrentWindow;
9664
180k
    SizeOfIDStack = (short)window->IDStack.Size;
9665
180k
    SizeOfColorStack = (short)g.ColorStack.Size;
9666
180k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
9667
180k
    SizeOfFontStack = (short)g.FontStack.Size;
9668
180k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
9669
180k
    SizeOfGroupStack = (short)g.GroupStack.Size;
9670
180k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
9671
180k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
9672
180k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
9673
180k
}
9674
9675
// Compare to detect usage errors
9676
void ImGuiStackSizes::CompareWithCurrentState()
9677
180k
{
9678
180k
    ImGuiContext& g = *GImGui;
9679
180k
    ImGuiWindow* window = g.CurrentWindow;
9680
180k
    IM_UNUSED(window);
9681
9682
    // Window stacks
9683
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
9684
180k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
9685
9686
    // Global stacks
9687
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
9688
180k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
9689
180k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
9690
180k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
9691
180k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
9692
180k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
9693
180k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
9694
180k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
9695
180k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
9696
180k
}
9697
9698
9699
//-----------------------------------------------------------------------------
9700
// [SECTION] LAYOUT
9701
//-----------------------------------------------------------------------------
9702
// - ItemSize()
9703
// - ItemAdd()
9704
// - SameLine()
9705
// - GetCursorScreenPos()
9706
// - SetCursorScreenPos()
9707
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
9708
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
9709
// - GetCursorStartPos()
9710
// - Indent()
9711
// - Unindent()
9712
// - SetNextItemWidth()
9713
// - PushItemWidth()
9714
// - PushMultiItemsWidths()
9715
// - PopItemWidth()
9716
// - CalcItemWidth()
9717
// - CalcItemSize()
9718
// - GetTextLineHeight()
9719
// - GetTextLineHeightWithSpacing()
9720
// - GetFrameHeight()
9721
// - GetFrameHeightWithSpacing()
9722
// - GetContentRegionMax()
9723
// - GetContentRegionMaxAbs() [Internal]
9724
// - GetContentRegionAvail(),
9725
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
9726
// - BeginGroup()
9727
// - EndGroup()
9728
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
9729
//-----------------------------------------------------------------------------
9730
9731
// Advance cursor given item size for layout.
9732
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
9733
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
9734
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
9735
622
{
9736
622
    ImGuiContext& g = *GImGui;
9737
622
    ImGuiWindow* window = g.CurrentWindow;
9738
622
    if (window->SkipItems)
9739
0
        return;
9740
9741
    // We increase the height in this function to accommodate for baseline offset.
9742
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
9743
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
9744
622
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
9745
9746
622
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
9747
622
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
9748
9749
    // Always align ourselves on pixel boundaries
9750
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
9751
622
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
9752
622
    window->DC.CursorPosPrevLine.y = line_y1;
9753
622
    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
9754
622
    window->DC.CursorPos.y = IM_FLOOR(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
9755
622
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
9756
622
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
9757
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
9758
9759
622
    window->DC.PrevLineSize.y = line_height;
9760
622
    window->DC.CurrLineSize.y = 0.0f;
9761
622
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
9762
622
    window->DC.CurrLineTextBaseOffset = 0.0f;
9763
622
    window->DC.IsSameLine = window->DC.IsSetPos = false;
9764
9765
    // Horizontal layout mode
9766
622
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9767
0
        SameLine();
9768
622
}
9769
9770
// Declare item bounding box for clipping and interaction.
9771
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
9772
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
9773
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
9774
181k
{
9775
181k
    ImGuiContext& g = *GImGui;
9776
181k
    ImGuiWindow* window = g.CurrentWindow;
9777
9778
    // Set item data
9779
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
9780
181k
    g.LastItemData.ID = id;
9781
181k
    g.LastItemData.Rect = bb;
9782
181k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
9783
181k
    g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;
9784
181k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
9785
9786
    // Directional navigation processing
9787
181k
    if (id != 0)
9788
181k
    {
9789
181k
        KeepAliveID(id);
9790
9791
        // Runs prior to clipping early-out
9792
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
9793
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
9794
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
9795
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
9796
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
9797
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
9798
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
9799
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
9800
181k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
9801
180k
        {
9802
180k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
9803
180k
            if (g.NavId == id || g.NavAnyRequest)
9804
126
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
9805
95
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
9806
95
                        NavProcessItem();
9807
180k
        }
9808
9809
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
9810
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
9811
        // READ THE FAQ: https://dearimgui.org/faq
9812
181k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
9813
181k
    }
9814
181k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
9815
9816
#ifdef IMGUI_ENABLE_TEST_ENGINE
9817
    if (id != 0)
9818
        IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
9819
#endif
9820
9821
    // Clipping test
9822
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
9823
    //const bool is_clipped = IsClippedEx(bb, id);
9824
    //if (is_clipped)
9825
    //    return false;
9826
181k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
9827
181k
    if (!is_rect_visible)
9828
78
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
9829
78
            if (!g.LogEnabled)
9830
78
                return false;
9831
9832
    // [DEBUG]
9833
181k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9834
181k
    if (id != 0 && id == g.DebugLocateId)
9835
0
        DebugLocateItemResolveWithLastItem();
9836
181k
#endif
9837
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
9838
9839
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
9840
181k
    if (is_rect_visible)
9841
181k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
9842
181k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
9843
5.01k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
9844
181k
    return true;
9845
181k
}
9846
9847
// Gets back to previous line and continue with horizontal layout
9848
//      offset_from_start_x == 0 : follow right after previous item
9849
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
9850
//      spacing_w < 0            : use default spacing if pos_x == 0, no spacing if pos_x != 0
9851
//      spacing_w >= 0           : enforce spacing amount
9852
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
9853
0
{
9854
0
    ImGuiContext& g = *GImGui;
9855
0
    ImGuiWindow* window = g.CurrentWindow;
9856
0
    if (window->SkipItems)
9857
0
        return;
9858
9859
0
    if (offset_from_start_x != 0.0f)
9860
0
    {
9861
0
        if (spacing_w < 0.0f)
9862
0
            spacing_w = 0.0f;
9863
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
9864
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
9865
0
    }
9866
0
    else
9867
0
    {
9868
0
        if (spacing_w < 0.0f)
9869
0
            spacing_w = g.Style.ItemSpacing.x;
9870
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
9871
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
9872
0
    }
9873
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
9874
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
9875
0
    window->DC.IsSameLine = true;
9876
0
}
9877
9878
ImVec2 ImGui::GetCursorScreenPos()
9879
398
{
9880
398
    ImGuiWindow* window = GetCurrentWindowRead();
9881
398
    return window->DC.CursorPos;
9882
398
}
9883
9884
// 2022/08/05: Setting cursor position also extend boundaries (via modifying CursorMaxPos) used to compute window size, group size etc.
9885
// I believe this was is a judicious choice but it's probably being relied upon (it has been the case since 1.31 and 1.50)
9886
// It would be sane if we requested user to use SetCursorPos() + Dummy(ImVec2(0,0)) to extend CursorMaxPos...
9887
void ImGui::SetCursorScreenPos(const ImVec2& pos)
9888
0
{
9889
0
    ImGuiWindow* window = GetCurrentWindow();
9890
0
    window->DC.CursorPos = pos;
9891
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9892
0
    window->DC.IsSetPos = true;
9893
0
}
9894
9895
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
9896
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
9897
ImVec2 ImGui::GetCursorPos()
9898
0
{
9899
0
    ImGuiWindow* window = GetCurrentWindowRead();
9900
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
9901
0
}
9902
9903
float ImGui::GetCursorPosX()
9904
0
{
9905
0
    ImGuiWindow* window = GetCurrentWindowRead();
9906
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
9907
0
}
9908
9909
float ImGui::GetCursorPosY()
9910
0
{
9911
0
    ImGuiWindow* window = GetCurrentWindowRead();
9912
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
9913
0
}
9914
9915
void ImGui::SetCursorPos(const ImVec2& local_pos)
9916
0
{
9917
0
    ImGuiWindow* window = GetCurrentWindow();
9918
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
9919
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9920
0
    window->DC.IsSetPos = true;
9921
0
}
9922
9923
void ImGui::SetCursorPosX(float x)
9924
0
{
9925
0
    ImGuiWindow* window = GetCurrentWindow();
9926
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
9927
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
9928
0
    window->DC.IsSetPos = true;
9929
0
}
9930
9931
void ImGui::SetCursorPosY(float y)
9932
0
{
9933
0
    ImGuiWindow* window = GetCurrentWindow();
9934
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
9935
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
9936
0
    window->DC.IsSetPos = true;
9937
0
}
9938
9939
ImVec2 ImGui::GetCursorStartPos()
9940
0
{
9941
0
    ImGuiWindow* window = GetCurrentWindowRead();
9942
0
    return window->DC.CursorStartPos - window->Pos;
9943
0
}
9944
9945
void ImGui::Indent(float indent_w)
9946
0
{
9947
0
    ImGuiContext& g = *GImGui;
9948
0
    ImGuiWindow* window = GetCurrentWindow();
9949
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
9950
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
9951
0
}
9952
9953
void ImGui::Unindent(float indent_w)
9954
0
{
9955
0
    ImGuiContext& g = *GImGui;
9956
0
    ImGuiWindow* window = GetCurrentWindow();
9957
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
9958
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
9959
0
}
9960
9961
// Affect large frame+labels widgets only.
9962
void ImGui::SetNextItemWidth(float item_width)
9963
0
{
9964
0
    ImGuiContext& g = *GImGui;
9965
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
9966
0
    g.NextItemData.Width = item_width;
9967
0
}
9968
9969
// FIXME: Remove the == 0.0f behavior?
9970
void ImGui::PushItemWidth(float item_width)
9971
0
{
9972
0
    ImGuiContext& g = *GImGui;
9973
0
    ImGuiWindow* window = g.CurrentWindow;
9974
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
9975
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
9976
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
9977
0
}
9978
9979
void ImGui::PushMultiItemsWidths(int components, float w_full)
9980
0
{
9981
0
    ImGuiContext& g = *GImGui;
9982
0
    ImGuiWindow* window = g.CurrentWindow;
9983
0
    const ImGuiStyle& style = g.Style;
9984
0
    const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
9985
0
    const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
9986
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
9987
0
    window->DC.ItemWidthStack.push_back(w_item_last);
9988
0
    for (int i = 0; i < components - 2; i++)
9989
0
        window->DC.ItemWidthStack.push_back(w_item_one);
9990
0
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
9991
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
9992
0
}
9993
9994
void ImGui::PopItemWidth()
9995
0
{
9996
0
    ImGuiWindow* window = GetCurrentWindow();
9997
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
9998
0
    window->DC.ItemWidthStack.pop_back();
9999
0
}
10000
10001
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10002
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10003
float ImGui::CalcItemWidth()
10004
0
{
10005
0
    ImGuiContext& g = *GImGui;
10006
0
    ImGuiWindow* window = g.CurrentWindow;
10007
0
    float w;
10008
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10009
0
        w = g.NextItemData.Width;
10010
0
    else
10011
0
        w = window->DC.ItemWidth;
10012
0
    if (w < 0.0f)
10013
0
    {
10014
0
        float region_max_x = GetContentRegionMaxAbs().x;
10015
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10016
0
    }
10017
0
    w = IM_FLOOR(w);
10018
0
    return w;
10019
0
}
10020
10021
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10022
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10023
// Note that only CalcItemWidth() is publicly exposed.
10024
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10025
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10026
0
{
10027
0
    ImGuiContext& g = *GImGui;
10028
0
    ImGuiWindow* window = g.CurrentWindow;
10029
10030
0
    ImVec2 region_max;
10031
0
    if (size.x < 0.0f || size.y < 0.0f)
10032
0
        region_max = GetContentRegionMaxAbs();
10033
10034
0
    if (size.x == 0.0f)
10035
0
        size.x = default_w;
10036
0
    else if (size.x < 0.0f)
10037
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10038
10039
0
    if (size.y == 0.0f)
10040
0
        size.y = default_h;
10041
0
    else if (size.y < 0.0f)
10042
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10043
10044
0
    return size;
10045
0
}
10046
10047
float ImGui::GetTextLineHeight()
10048
0
{
10049
0
    ImGuiContext& g = *GImGui;
10050
0
    return g.FontSize;
10051
0
}
10052
10053
float ImGui::GetTextLineHeightWithSpacing()
10054
311
{
10055
311
    ImGuiContext& g = *GImGui;
10056
311
    return g.FontSize + g.Style.ItemSpacing.y;
10057
311
}
10058
10059
float ImGui::GetFrameHeight()
10060
59
{
10061
59
    ImGuiContext& g = *GImGui;
10062
59
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10063
59
}
10064
10065
float ImGui::GetFrameHeightWithSpacing()
10066
0
{
10067
0
    ImGuiContext& g = *GImGui;
10068
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10069
0
}
10070
10071
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10072
10073
// FIXME: This is in window space (not screen space!).
10074
ImVec2 ImGui::GetContentRegionMax()
10075
0
{
10076
0
    ImGuiContext& g = *GImGui;
10077
0
    ImGuiWindow* window = g.CurrentWindow;
10078
0
    ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
10079
0
    if (window->DC.CurrentColumns || g.CurrentTable)
10080
0
        mx.x = window->WorkRect.Max.x - window->Pos.x;
10081
0
    return mx;
10082
0
}
10083
10084
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10085
ImVec2 ImGui::GetContentRegionMaxAbs()
10086
311
{
10087
311
    ImGuiContext& g = *GImGui;
10088
311
    ImGuiWindow* window = g.CurrentWindow;
10089
311
    ImVec2 mx = window->ContentRegionRect.Max;
10090
311
    if (window->DC.CurrentColumns || g.CurrentTable)
10091
0
        mx.x = window->WorkRect.Max.x;
10092
311
    return mx;
10093
311
}
10094
10095
ImVec2 ImGui::GetContentRegionAvail()
10096
311
{
10097
311
    ImGuiWindow* window = GImGui->CurrentWindow;
10098
311
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10099
311
}
10100
10101
// In window space (not screen space!)
10102
ImVec2 ImGui::GetWindowContentRegionMin()
10103
0
{
10104
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10105
0
    return window->ContentRegionRect.Min - window->Pos;
10106
0
}
10107
10108
ImVec2 ImGui::GetWindowContentRegionMax()
10109
311
{
10110
311
    ImGuiWindow* window = GImGui->CurrentWindow;
10111
311
    return window->ContentRegionRect.Max - window->Pos;
10112
311
}
10113
10114
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10115
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10116
// FIXME-OPT: Could we safely early out on ->SkipItems?
10117
void ImGui::BeginGroup()
10118
0
{
10119
0
    ImGuiContext& g = *GImGui;
10120
0
    ImGuiWindow* window = g.CurrentWindow;
10121
10122
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10123
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10124
0
    group_data.WindowID = window->ID;
10125
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10126
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10127
0
    group_data.BackupIndent = window->DC.Indent;
10128
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10129
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10130
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10131
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10132
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10133
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10134
0
    group_data.EmitItem = true;
10135
10136
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10137
0
    window->DC.Indent = window->DC.GroupOffset;
10138
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10139
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10140
0
    if (g.LogEnabled)
10141
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10142
0
}
10143
10144
void ImGui::EndGroup()
10145
0
{
10146
0
    ImGuiContext& g = *GImGui;
10147
0
    ImGuiWindow* window = g.CurrentWindow;
10148
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10149
10150
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10151
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10152
10153
0
    if (window->DC.IsSetPos)
10154
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10155
10156
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10157
10158
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10159
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10160
0
    window->DC.Indent = group_data.BackupIndent;
10161
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10162
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10163
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10164
0
    if (g.LogEnabled)
10165
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10166
10167
0
    if (!group_data.EmitItem)
10168
0
    {
10169
0
        g.GroupStack.pop_back();
10170
0
        return;
10171
0
    }
10172
10173
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10174
0
    ItemSize(group_bb.GetSize());
10175
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10176
10177
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10178
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10179
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10180
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10181
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10182
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10183
0
    if (group_contains_curr_active_id)
10184
0
        g.LastItemData.ID = g.ActiveId;
10185
0
    else if (group_contains_prev_active_id)
10186
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10187
0
    g.LastItemData.Rect = group_bb;
10188
10189
    // Forward Hovered flag
10190
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10191
0
    if (group_contains_curr_hovered_id)
10192
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10193
10194
    // Forward Edited flag
10195
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10196
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10197
10198
    // Forward Deactivated flag
10199
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10200
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10201
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10202
10203
0
    g.GroupStack.pop_back();
10204
    //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10205
0
}
10206
10207
10208
//-----------------------------------------------------------------------------
10209
// [SECTION] SCROLLING
10210
//-----------------------------------------------------------------------------
10211
10212
// Helper to snap on edges when aiming at an item very close to the edge,
10213
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10214
// When we refactor the scrolling API this may be configurable with a flag?
10215
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10216
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10217
0
{
10218
0
    if (target <= snap_min + snap_threshold)
10219
0
        return ImLerp(snap_min, target, center_ratio);
10220
0
    if (target >= snap_max - snap_threshold)
10221
0
        return ImLerp(target, snap_max, center_ratio);
10222
0
    return target;
10223
0
}
10224
10225
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10226
180k
{
10227
180k
    ImVec2 scroll = window->Scroll;
10228
180k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10229
542k
    for (int axis = 0; axis < 2; axis++)
10230
361k
    {
10231
361k
        if (window->ScrollTarget[axis] < FLT_MAX)
10232
179
        {
10233
179
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10234
179
            float scroll_target = window->ScrollTarget[axis];
10235
179
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10236
0
            {
10237
0
                float snap_min = 0.0f;
10238
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10239
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10240
0
            }
10241
179
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10242
179
        }
10243
361k
        scroll[axis] = IM_FLOOR(ImMax(scroll[axis], 0.0f));
10244
361k
        if (!window->Collapsed && !window->SkipItems)
10245
181k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10246
361k
    }
10247
180k
    return scroll;
10248
180k
}
10249
10250
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10251
0
{
10252
0
    ImGuiContext& g = *GImGui;
10253
0
    ImGuiWindow* window = g.CurrentWindow;
10254
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10255
0
}
10256
10257
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10258
0
{
10259
0
    ScrollToRectEx(window, item_rect, flags);
10260
0
}
10261
10262
// Scroll to keep newly navigated item fully into view
10263
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10264
0
{
10265
0
    ImGuiContext& g = *GImGui;
10266
0
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10267
0
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10268
0
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10269
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10270
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10271
10272
    // Check that only one behavior is selected per axis
10273
0
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10274
0
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10275
10276
    // Defaults
10277
0
    ImGuiScrollFlags in_flags = flags;
10278
0
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10279
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10280
0
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10281
0
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10282
10283
0
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10284
0
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10285
0
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10286
0
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10287
10288
0
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10289
0
    {
10290
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10291
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10292
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10293
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10294
0
    }
10295
0
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10296
0
    {
10297
0
        if (can_be_fully_visible_x)
10298
0
            SetScrollFromPosX(window, ImFloor((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10299
0
        else
10300
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10301
0
    }
10302
10303
0
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10304
0
    {
10305
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10306
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10307
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10308
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10309
0
    }
10310
0
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10311
0
    {
10312
0
        if (can_be_fully_visible_y)
10313
0
            SetScrollFromPosY(window, ImFloor((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10314
0
        else
10315
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10316
0
    }
10317
10318
0
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10319
0
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10320
10321
    // Also scroll parent window to keep us into view if necessary
10322
0
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10323
0
    {
10324
        // FIXME-SCROLL: May be an option?
10325
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10326
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10327
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10328
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10329
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10330
0
    }
10331
10332
0
    return delta_scroll;
10333
0
}
10334
10335
float ImGui::GetScrollX()
10336
397
{
10337
397
    ImGuiWindow* window = GImGui->CurrentWindow;
10338
397
    return window->Scroll.x;
10339
397
}
10340
10341
float ImGui::GetScrollY()
10342
397
{
10343
397
    ImGuiWindow* window = GImGui->CurrentWindow;
10344
397
    return window->Scroll.y;
10345
397
}
10346
10347
float ImGui::GetScrollMaxX()
10348
0
{
10349
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10350
0
    return window->ScrollMax.x;
10351
0
}
10352
10353
float ImGui::GetScrollMaxY()
10354
0
{
10355
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10356
0
    return window->ScrollMax.y;
10357
0
}
10358
10359
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10360
86
{
10361
86
    window->ScrollTarget.x = scroll_x;
10362
86
    window->ScrollTargetCenterRatio.x = 0.0f;
10363
86
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10364
86
}
10365
10366
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10367
94
{
10368
94
    window->ScrollTarget.y = scroll_y;
10369
94
    window->ScrollTargetCenterRatio.y = 0.0f;
10370
94
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10371
94
}
10372
10373
void ImGui::SetScrollX(float scroll_x)
10374
86
{
10375
86
    ImGuiContext& g = *GImGui;
10376
86
    SetScrollX(g.CurrentWindow, scroll_x);
10377
86
}
10378
10379
void ImGui::SetScrollY(float scroll_y)
10380
93
{
10381
93
    ImGuiContext& g = *GImGui;
10382
93
    SetScrollY(g.CurrentWindow, scroll_y);
10383
93
}
10384
10385
// Note that a local position will vary depending on initial scroll value,
10386
// This is a little bit confusing so bear with us:
10387
//  - local_pos = (absolution_pos - window->Pos)
10388
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10389
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10390
//  - They mostly exist because of legacy API.
10391
// Following the rules above, when trying to work with scrolling code, consider that:
10392
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10393
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10394
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10395
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10396
0
{
10397
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10398
0
    window->ScrollTarget.x = IM_FLOOR(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10399
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10400
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10401
0
}
10402
10403
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10404
0
{
10405
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10406
0
    window->ScrollTarget.y = IM_FLOOR(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10407
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10408
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10409
0
}
10410
10411
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10412
0
{
10413
0
    ImGuiContext& g = *GImGui;
10414
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10415
0
}
10416
10417
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10418
0
{
10419
0
    ImGuiContext& g = *GImGui;
10420
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10421
0
}
10422
10423
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10424
void ImGui::SetScrollHereX(float center_x_ratio)
10425
0
{
10426
0
    ImGuiContext& g = *GImGui;
10427
0
    ImGuiWindow* window = g.CurrentWindow;
10428
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10429
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10430
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10431
10432
    // Tweak: snap on edges when aiming at an item very close to the edge
10433
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10434
0
}
10435
10436
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10437
void ImGui::SetScrollHereY(float center_y_ratio)
10438
0
{
10439
0
    ImGuiContext& g = *GImGui;
10440
0
    ImGuiWindow* window = g.CurrentWindow;
10441
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10442
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10443
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10444
10445
    // Tweak: snap on edges when aiming at an item very close to the edge
10446
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10447
0
}
10448
10449
//-----------------------------------------------------------------------------
10450
// [SECTION] TOOLTIPS
10451
//-----------------------------------------------------------------------------
10452
10453
void ImGui::BeginTooltip()
10454
0
{
10455
0
    BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10456
0
}
10457
10458
void ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10459
0
{
10460
0
    ImGuiContext& g = *GImGui;
10461
10462
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
10463
0
    {
10464
        // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
10465
        // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
10466
        // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
10467
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10468
0
        ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
10469
0
        SetNextWindowPos(tooltip_pos);
10470
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
10471
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
10472
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
10473
0
    }
10474
10475
0
    char window_name[16];
10476
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
10477
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
10478
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
10479
0
            if (window->Active)
10480
0
            {
10481
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
10482
0
                window->Hidden = true;
10483
0
                window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?
10484
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
10485
0
            }
10486
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
10487
0
    Begin(window_name, NULL, flags | extra_window_flags);
10488
0
}
10489
10490
void ImGui::EndTooltip()
10491
0
{
10492
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
10493
0
    End();
10494
0
}
10495
10496
void ImGui::SetTooltipV(const char* fmt, va_list args)
10497
0
{
10498
0
    BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None);
10499
0
    TextV(fmt, args);
10500
0
    EndTooltip();
10501
0
}
10502
10503
void ImGui::SetTooltip(const char* fmt, ...)
10504
0
{
10505
0
    va_list args;
10506
0
    va_start(args, fmt);
10507
0
    SetTooltipV(fmt, args);
10508
0
    va_end(args);
10509
0
}
10510
10511
//-----------------------------------------------------------------------------
10512
// [SECTION] POPUPS
10513
//-----------------------------------------------------------------------------
10514
10515
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
10516
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
10517
0
{
10518
0
    ImGuiContext& g = *GImGui;
10519
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
10520
0
    {
10521
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
10522
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
10523
0
        IM_ASSERT(id == 0);
10524
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10525
0
            return g.OpenPopupStack.Size > 0;
10526
0
        else
10527
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
10528
0
    }
10529
0
    else
10530
0
    {
10531
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10532
0
        {
10533
            // Return true if the popup is open anywhere in the popup stack
10534
0
            for (int n = 0; n < g.OpenPopupStack.Size; n++)
10535
0
                if (g.OpenPopupStack[n].PopupId == id)
10536
0
                    return true;
10537
0
            return false;
10538
0
        }
10539
0
        else
10540
0
        {
10541
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
10542
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
10543
0
        }
10544
0
    }
10545
0
}
10546
10547
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
10548
0
{
10549
0
    ImGuiContext& g = *GImGui;
10550
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
10551
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
10552
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
10553
0
    return IsPopupOpen(id, popup_flags);
10554
0
}
10555
10556
ImGuiWindow* ImGui::GetTopMostPopupModal()
10557
271k
{
10558
271k
    ImGuiContext& g = *GImGui;
10559
271k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10560
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10561
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
10562
0
                return popup;
10563
271k
    return NULL;
10564
271k
}
10565
10566
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
10567
90.2k
{
10568
90.2k
    ImGuiContext& g = *GImGui;
10569
90.2k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10570
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10571
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
10572
0
                return popup;
10573
90.2k
    return NULL;
10574
90.2k
}
10575
10576
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
10577
0
{
10578
0
    ImGuiContext& g = *GImGui;
10579
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10580
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X\n", str_id, id);
10581
0
    OpenPopupEx(id, popup_flags);
10582
0
}
10583
10584
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
10585
0
{
10586
0
    OpenPopupEx(id, popup_flags);
10587
0
}
10588
10589
// Mark popup as open (toggle toward open state).
10590
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
10591
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
10592
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
10593
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
10594
0
{
10595
0
    ImGuiContext& g = *GImGui;
10596
0
    ImGuiWindow* parent_window = g.CurrentWindow;
10597
0
    const int current_stack_size = g.BeginPopupStack.Size;
10598
10599
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
10600
0
        if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))
10601
0
            return;
10602
10603
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
10604
0
    popup_ref.PopupId = id;
10605
0
    popup_ref.Window = NULL;
10606
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
10607
0
    popup_ref.OpenFrameCount = g.FrameCount;
10608
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
10609
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
10610
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
10611
10612
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
10613
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
10614
0
    {
10615
0
        g.OpenPopupStack.push_back(popup_ref);
10616
0
    }
10617
0
    else
10618
0
    {
10619
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
10620
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
10621
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
10622
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
10623
0
        {
10624
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
10625
0
        }
10626
0
        else
10627
0
        {
10628
            // Close child popups if any, then flag popup for open/reopen
10629
0
            ClosePopupToLevel(current_stack_size, false);
10630
0
            g.OpenPopupStack.push_back(popup_ref);
10631
0
        }
10632
10633
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
10634
        // This is equivalent to what ClosePopupToLevel() does.
10635
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
10636
        //    FocusWindow(parent_window);
10637
0
    }
10638
0
}
10639
10640
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
10641
// This function closes any popups that are over 'ref_window'.
10642
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
10643
615
{
10644
615
    ImGuiContext& g = *GImGui;
10645
615
    if (g.OpenPopupStack.Size == 0)
10646
615
        return;
10647
10648
    // Don't close our own child popup windows.
10649
0
    int popup_count_to_keep = 0;
10650
0
    if (ref_window)
10651
0
    {
10652
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
10653
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
10654
0
        {
10655
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
10656
0
            if (!popup.Window)
10657
0
                continue;
10658
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
10659
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
10660
0
                continue;
10661
10662
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
10663
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
10664
            //     Window -> Popup1 -> Popup2 -> Popup3
10665
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
10666
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
10667
0
            bool ref_window_is_descendent_of_popup = false;
10668
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
10669
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
10670
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
10671
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
10672
0
                    {
10673
0
                        ref_window_is_descendent_of_popup = true;
10674
0
                        break;
10675
0
                    }
10676
0
            if (!ref_window_is_descendent_of_popup)
10677
0
                break;
10678
0
        }
10679
0
    }
10680
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10681
0
    {
10682
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
10683
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
10684
0
    }
10685
0
}
10686
10687
void ImGui::ClosePopupsExceptModals()
10688
0
{
10689
0
    ImGuiContext& g = *GImGui;
10690
10691
0
    int popup_count_to_keep;
10692
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
10693
0
    {
10694
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
10695
0
        if (!window || window->Flags & ImGuiWindowFlags_Modal)
10696
0
            break;
10697
0
    }
10698
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10699
0
        ClosePopupToLevel(popup_count_to_keep, true);
10700
0
}
10701
10702
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
10703
0
{
10704
0
    ImGuiContext& g = *GImGui;
10705
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
10706
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
10707
10708
    // Trim open popup stack
10709
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
10710
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
10711
0
    g.OpenPopupStack.resize(remaining);
10712
10713
0
    if (restore_focus_to_window_under_popup)
10714
0
    {
10715
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
10716
0
        if (focus_window && !focus_window->WasActive && popup_window)
10717
0
        {
10718
            // Fallback
10719
0
            FocusTopMostWindowUnderOne(popup_window, NULL);
10720
0
        }
10721
0
        else
10722
0
        {
10723
0
            if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
10724
0
                focus_window = NavRestoreLastChildNavWindow(focus_window);
10725
0
            FocusWindow(focus_window);
10726
0
        }
10727
0
    }
10728
0
}
10729
10730
// Close the popup we have begin-ed into.
10731
void ImGui::CloseCurrentPopup()
10732
0
{
10733
0
    ImGuiContext& g = *GImGui;
10734
0
    int popup_idx = g.BeginPopupStack.Size - 1;
10735
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
10736
0
        return;
10737
10738
    // Closing a menu closes its top-most parent popup (unless a modal)
10739
0
    while (popup_idx > 0)
10740
0
    {
10741
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
10742
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
10743
0
        bool close_parent = false;
10744
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
10745
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
10746
0
                close_parent = true;
10747
0
        if (!close_parent)
10748
0
            break;
10749
0
        popup_idx--;
10750
0
    }
10751
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
10752
0
    ClosePopupToLevel(popup_idx, true);
10753
10754
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
10755
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
10756
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
10757
0
    if (ImGuiWindow* window = g.NavWindow)
10758
0
        window->DC.NavHideHighlightOneFrame = true;
10759
0
}
10760
10761
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
10762
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
10763
0
{
10764
0
    ImGuiContext& g = *GImGui;
10765
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10766
0
    {
10767
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10768
0
        return false;
10769
0
    }
10770
10771
0
    char name[20];
10772
0
    if (flags & ImGuiWindowFlags_ChildMenu)
10773
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
10774
0
    else
10775
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
10776
10777
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
10778
0
    bool is_open = Begin(name, NULL, flags);
10779
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
10780
0
        EndPopup();
10781
10782
0
    return is_open;
10783
0
}
10784
10785
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
10786
0
{
10787
0
    ImGuiContext& g = *GImGui;
10788
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
10789
0
    {
10790
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10791
0
        return false;
10792
0
    }
10793
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
10794
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10795
0
    return BeginPopupEx(id, flags);
10796
0
}
10797
10798
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
10799
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
10800
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
10801
0
{
10802
0
    ImGuiContext& g = *GImGui;
10803
0
    ImGuiWindow* window = g.CurrentWindow;
10804
0
    const ImGuiID id = window->GetID(name);
10805
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10806
0
    {
10807
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10808
0
        return false;
10809
0
    }
10810
10811
    // Center modal windows by default for increased visibility
10812
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
10813
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
10814
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
10815
0
    {
10816
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
10817
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
10818
0
    }
10819
10820
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
10821
0
    const bool is_open = Begin(name, p_open, flags);
10822
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
10823
0
    {
10824
0
        EndPopup();
10825
0
        if (is_open)
10826
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
10827
0
        return false;
10828
0
    }
10829
0
    return is_open;
10830
0
}
10831
10832
void ImGui::EndPopup()
10833
0
{
10834
0
    ImGuiContext& g = *GImGui;
10835
0
    ImGuiWindow* window = g.CurrentWindow;
10836
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
10837
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
10838
10839
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
10840
0
    if (g.NavWindow == window)
10841
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
10842
10843
    // Child-popups don't need to be laid out
10844
0
    IM_ASSERT(g.WithinEndChild == false);
10845
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
10846
0
        g.WithinEndChild = true;
10847
0
    End();
10848
0
    g.WithinEndChild = false;
10849
0
}
10850
10851
// Helper to open a popup if mouse button is released over the item
10852
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
10853
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
10854
0
{
10855
0
    ImGuiContext& g = *GImGui;
10856
0
    ImGuiWindow* window = g.CurrentWindow;
10857
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10858
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10859
0
    {
10860
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
10861
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
10862
0
        OpenPopupEx(id, popup_flags);
10863
0
    }
10864
0
}
10865
10866
// This is a helper to handle the simplest case of associating one named popup to one given widget.
10867
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
10868
// - To create a popup with a specific identifier, pass it in str_id.
10869
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
10870
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
10871
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
10872
//   This is essentially the same as:
10873
//       id = str_id ? GetID(str_id) : GetItemID();
10874
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
10875
//       return BeginPopup(id);
10876
//   Which is essentially the same as:
10877
//       id = str_id ? GetID(str_id) : GetItemID();
10878
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
10879
//           OpenPopup(id);
10880
//       return BeginPopup(id);
10881
//   The main difference being that this is tweaked to avoid computing the ID twice.
10882
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
10883
0
{
10884
0
    ImGuiContext& g = *GImGui;
10885
0
    ImGuiWindow* window = g.CurrentWindow;
10886
0
    if (window->SkipItems)
10887
0
        return false;
10888
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
10889
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
10890
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10891
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10892
0
        OpenPopupEx(id, popup_flags);
10893
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10894
0
}
10895
10896
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
10897
0
{
10898
0
    ImGuiContext& g = *GImGui;
10899
0
    ImGuiWindow* window = g.CurrentWindow;
10900
0
    if (!str_id)
10901
0
        str_id = "window_context";
10902
0
    ImGuiID id = window->GetID(str_id);
10903
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10904
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10905
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
10906
0
            OpenPopupEx(id, popup_flags);
10907
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10908
0
}
10909
10910
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
10911
0
{
10912
0
    ImGuiContext& g = *GImGui;
10913
0
    ImGuiWindow* window = g.CurrentWindow;
10914
0
    if (!str_id)
10915
0
        str_id = "void_context";
10916
0
    ImGuiID id = window->GetID(str_id);
10917
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10918
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
10919
0
        if (GetTopMostPopupModal() == NULL)
10920
0
            OpenPopupEx(id, popup_flags);
10921
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10922
0
}
10923
10924
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
10925
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
10926
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
10927
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
10928
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
10929
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
10930
0
{
10931
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
10932
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
10933
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
10934
10935
    // Combo Box policy (we want a connecting edge)
10936
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
10937
0
    {
10938
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
10939
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
10940
0
        {
10941
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
10942
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
10943
0
                continue;
10944
0
            ImVec2 pos;
10945
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
10946
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
10947
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
10948
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
10949
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
10950
0
                continue;
10951
0
            *last_dir = dir;
10952
0
            return pos;
10953
0
        }
10954
0
    }
10955
10956
    // Tooltip and Default popup policy
10957
    // (Always first try the direction we used on the last frame, if any)
10958
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
10959
0
    {
10960
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
10961
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
10962
0
        {
10963
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
10964
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
10965
0
                continue;
10966
10967
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
10968
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
10969
10970
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
10971
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
10972
0
                continue;
10973
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
10974
0
                continue;
10975
10976
0
            ImVec2 pos;
10977
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
10978
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
10979
10980
            // Clamp top-left corner of popup
10981
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
10982
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
10983
10984
0
            *last_dir = dir;
10985
0
            return pos;
10986
0
        }
10987
0
    }
10988
10989
    // Fallback when not enough room:
10990
0
    *last_dir = ImGuiDir_None;
10991
10992
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
10993
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
10994
0
        return ref_pos + ImVec2(2, 2);
10995
10996
    // Otherwise try to keep within display
10997
0
    ImVec2 pos = ref_pos;
10998
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
10999
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11000
0
    return pos;
11001
0
}
11002
11003
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11004
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11005
0
{
11006
0
    ImGuiContext& g = *GImGui;
11007
0
    ImRect r_screen;
11008
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11009
0
    {
11010
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11011
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11012
0
        r_screen.Min = monitor.WorkPos;
11013
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11014
0
    }
11015
0
    else
11016
0
    {
11017
        // Use the full viewport area (not work area) for popups
11018
0
        r_screen = window->Viewport->GetMainRect();
11019
0
    }
11020
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11021
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11022
0
    return r_screen;
11023
0
}
11024
11025
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11026
0
{
11027
0
    ImGuiContext& g = *GImGui;
11028
11029
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11030
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11031
0
    {
11032
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11033
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11034
0
        ImGuiWindow* parent_window = window->ParentWindow;
11035
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11036
0
        ImRect r_avoid;
11037
0
        if (parent_window->DC.MenuBarAppending)
11038
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11039
0
        else
11040
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11041
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11042
0
    }
11043
0
    if (window->Flags & ImGuiWindowFlags_Popup)
11044
0
    {
11045
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11046
0
    }
11047
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11048
0
    {
11049
        // Position tooltip (always follows mouse)
11050
0
        float sc = g.Style.MouseCursorScale;
11051
0
        ImVec2 ref_pos = NavCalcPreferredRefPos();
11052
0
        ImRect r_avoid;
11053
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11054
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11055
0
        else
11056
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11057
0
        return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11058
0
    }
11059
0
    IM_ASSERT(0);
11060
0
    return window->Pos;
11061
0
}
11062
11063
//-----------------------------------------------------------------------------
11064
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11065
//-----------------------------------------------------------------------------
11066
11067
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11068
// In our terminology those should be interchangeable, yet right now this is super confusing.
11069
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11070
11071
void ImGui::SetNavWindow(ImGuiWindow* window)
11072
124
{
11073
124
    ImGuiContext& g = *GImGui;
11074
124
    if (g.NavWindow != window)
11075
124
    {
11076
124
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11077
124
        g.NavWindow = window;
11078
124
    }
11079
124
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11080
124
    NavUpdateAnyRequestFlag();
11081
124
}
11082
11083
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11084
6
{
11085
6
    ImGuiContext& g = *GImGui;
11086
6
    IM_ASSERT(g.NavWindow != NULL);
11087
6
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11088
6
    g.NavId = id;
11089
6
    g.NavLayer = nav_layer;
11090
6
    g.NavFocusScopeId = focus_scope_id;
11091
6
    g.NavWindow->NavLastIds[nav_layer] = id;
11092
6
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11093
6
}
11094
11095
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11096
27
{
11097
27
    ImGuiContext& g = *GImGui;
11098
27
    IM_ASSERT(id != 0);
11099
11100
27
    if (g.NavWindow != window)
11101
20
       SetNavWindow(window);
11102
11103
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11104
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11105
27
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11106
27
    g.NavId = id;
11107
27
    g.NavLayer = nav_layer;
11108
27
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11109
27
    window->NavLastIds[nav_layer] = id;
11110
27
    if (g.LastItemData.ID == id)
11111
27
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11112
11113
27
    if (g.ActiveIdSource == ImGuiInputSource_Nav)
11114
0
        g.NavDisableMouseHover = true;
11115
27
    else
11116
27
        g.NavDisableHighlight = true;
11117
27
}
11118
11119
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11120
0
{
11121
0
    if (ImFabs(dx) > ImFabs(dy))
11122
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11123
0
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11124
0
}
11125
11126
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
11127
0
{
11128
0
    if (a1 < b0)
11129
0
        return a1 - b0;
11130
0
    if (b1 < a0)
11131
0
        return a0 - b1;
11132
0
    return 0.0f;
11133
0
}
11134
11135
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
11136
0
{
11137
0
    if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11138
0
    {
11139
0
        r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
11140
0
        r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
11141
0
    }
11142
0
    else // FIXME: PageUp/PageDown are leaving move_dir == None
11143
0
    {
11144
0
        r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
11145
0
        r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
11146
0
    }
11147
0
}
11148
11149
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11150
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11151
6
{
11152
6
    ImGuiContext& g = *GImGui;
11153
6
    ImGuiWindow* window = g.CurrentWindow;
11154
6
    if (g.NavLayer != window->DC.NavLayerCurrent)
11155
6
        return false;
11156
11157
    // FIXME: Those are not good variables names
11158
0
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11159
0
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11160
0
    g.NavScoringDebugCount++;
11161
11162
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11163
0
    if (window->ParentWindow == g.NavWindow)
11164
0
    {
11165
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11166
0
        if (!window->ClipRect.Overlaps(cand))
11167
0
            return false;
11168
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11169
0
    }
11170
11171
    // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
11172
    // For example, this ensures that items in one column are not reached when moving vertically from items in another column.
11173
0
    NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
11174
11175
    // Compute distance between boxes
11176
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11177
0
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11178
0
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11179
0
    if (dby != 0.0f && dbx != 0.0f)
11180
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11181
0
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11182
11183
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11184
0
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11185
0
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11186
0
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11187
11188
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11189
0
    ImGuiDir quadrant;
11190
0
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11191
0
    if (dbx != 0.0f || dby != 0.0f)
11192
0
    {
11193
        // For non-overlapping boxes, use distance between boxes
11194
0
        dax = dbx;
11195
0
        day = dby;
11196
0
        dist_axial = dist_box;
11197
0
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11198
0
    }
11199
0
    else if (dcx != 0.0f || dcy != 0.0f)
11200
0
    {
11201
        // For overlapping boxes with different centers, use distance between centers
11202
0
        dax = dcx;
11203
0
        day = dcy;
11204
0
        dist_axial = dist_center;
11205
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11206
0
    }
11207
0
    else
11208
0
    {
11209
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11210
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11211
0
    }
11212
11213
#if IMGUI_DEBUG_NAV_SCORING
11214
    char buf[128];
11215
    if (IsMouseHoveringRect(cand.Min, cand.Max))
11216
    {
11217
        ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
11218
        ImDrawList* draw_list = GetForegroundDrawList(window);
11219
        draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
11220
        draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
11221
        draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
11222
        draw_list->AddText(cand.Max, ~0U, buf);
11223
    }
11224
    else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
11225
    {
11226
        if (quadrant == g.NavMoveDir)
11227
        {
11228
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11229
            ImDrawList* draw_list = GetForegroundDrawList(window);
11230
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
11231
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11232
        }
11233
    }
11234
#endif
11235
11236
    // Is it in the quadrant we're interested in moving to?
11237
0
    bool new_best = false;
11238
0
    const ImGuiDir move_dir = g.NavMoveDir;
11239
0
    if (quadrant == move_dir)
11240
0
    {
11241
        // Does it beat the current best candidate?
11242
0
        if (dist_box < result->DistBox)
11243
0
        {
11244
0
            result->DistBox = dist_box;
11245
0
            result->DistCenter = dist_center;
11246
0
            return true;
11247
0
        }
11248
0
        if (dist_box == result->DistBox)
11249
0
        {
11250
            // Try using distance between center points to break ties
11251
0
            if (dist_center < result->DistCenter)
11252
0
            {
11253
0
                result->DistCenter = dist_center;
11254
0
                new_best = true;
11255
0
            }
11256
0
            else if (dist_center == result->DistCenter)
11257
0
            {
11258
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11259
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11260
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11261
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11262
0
                    new_best = true;
11263
0
            }
11264
0
        }
11265
0
    }
11266
11267
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11268
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11269
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11270
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11271
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11272
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11273
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11274
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11275
0
            {
11276
0
                result->DistAxial = dist_axial;
11277
0
                new_best = true;
11278
0
            }
11279
11280
0
    return new_best;
11281
0
}
11282
11283
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11284
0
{
11285
0
    ImGuiContext& g = *GImGui;
11286
0
    ImGuiWindow* window = g.CurrentWindow;
11287
0
    result->Window = window;
11288
0
    result->ID = g.LastItemData.ID;
11289
0
    result->FocusScopeId = g.CurrentFocusScopeId;
11290
0
    result->InFlags = g.LastItemData.InFlags;
11291
0
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11292
0
}
11293
11294
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11295
// This is called after LastItemData is set.
11296
static void ImGui::NavProcessItem()
11297
95
{
11298
95
    ImGuiContext& g = *GImGui;
11299
95
    ImGuiWindow* window = g.CurrentWindow;
11300
95
    const ImGuiID id = g.LastItemData.ID;
11301
95
    const ImRect nav_bb = g.LastItemData.NavRect;
11302
95
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11303
11304
    // Process Init Request
11305
95
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11306
0
    {
11307
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11308
0
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11309
0
        if (candidate_for_nav_default_focus || g.NavInitResultId == 0)
11310
0
        {
11311
0
            g.NavInitResultId = id;
11312
0
            g.NavInitResultRectRel = WindowRectAbsToRel(window, nav_bb);
11313
0
        }
11314
0
        if (candidate_for_nav_default_focus)
11315
0
        {
11316
0
            g.NavInitRequest = false; // Found a match, clear request
11317
0
            NavUpdateAnyRequestFlag();
11318
0
        }
11319
0
    }
11320
11321
    // Process Move Request (scoring for navigation)
11322
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11323
95
    if (g.NavMoveScoringItems)
11324
3
    {
11325
3
        const bool is_tab_stop = (item_flags & ImGuiItemFlags_Inputable) && (item_flags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
11326
3
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;
11327
3
        if (is_tabbing)
11328
0
        {
11329
0
            if (is_tab_stop || (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi))
11330
0
                NavProcessItemForTabbingRequest(id);
11331
0
        }
11332
3
        else if ((g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & ImGuiItemFlags_Disabled))
11333
3
        {
11334
3
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11335
3
            if (!is_tabbing)
11336
3
            {
11337
3
                if (NavScoreItem(result))
11338
0
                    NavApplyItemToResult(result);
11339
11340
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11341
3
                const float VISIBLE_RATIO = 0.70f;
11342
3
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11343
3
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11344
3
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
11345
0
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11346
3
            }
11347
3
        }
11348
3
    }
11349
11350
    // Update window-relative bounding box of navigated item
11351
95
    if (g.NavId == id)
11352
90
    {
11353
90
        if (g.NavWindow != window)
11354
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11355
90
        g.NavLayer = window->DC.NavLayerCurrent;
11356
90
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11357
90
        g.NavIdIsAlive = true;
11358
90
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb);    // Store item bounding box (relative to window position)
11359
90
    }
11360
95
}
11361
11362
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11363
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11364
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11365
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11366
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11367
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11368
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11369
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id)
11370
0
{
11371
0
    ImGuiContext& g = *GImGui;
11372
11373
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11374
0
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11375
0
    if (g.NavTabbingDir == +1)
11376
0
    {
11377
        // Tab Forward or SetKeyboardFocusHere() with >= 0
11378
0
        if (g.NavTabbingResultFirst.ID == 0)
11379
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11380
0
        if (--g.NavTabbingCounter == 0)
11381
0
            NavMoveRequestResolveWithLastItem(result);
11382
0
        else if (g.NavId == id)
11383
0
            g.NavTabbingCounter = 1;
11384
0
    }
11385
0
    else if (g.NavTabbingDir == -1)
11386
0
    {
11387
        // Tab Backward
11388
0
        if (g.NavId == id)
11389
0
        {
11390
0
            if (result->ID)
11391
0
            {
11392
0
                g.NavMoveScoringItems = false;
11393
0
                NavUpdateAnyRequestFlag();
11394
0
            }
11395
0
        }
11396
0
        else
11397
0
        {
11398
0
            NavApplyItemToResult(result);
11399
0
        }
11400
0
    }
11401
0
    else if (g.NavTabbingDir == 0)
11402
0
    {
11403
        // Tab Init
11404
0
        if (g.NavTabbingResultFirst.ID == 0)
11405
0
            NavMoveRequestResolveWithLastItem(&g.NavTabbingResultFirst);
11406
0
    }
11407
0
}
11408
11409
bool ImGui::NavMoveRequestButNoResultYet()
11410
403
{
11411
403
    ImGuiContext& g = *GImGui;
11412
403
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
11413
403
}
11414
11415
// FIXME: ScoringRect is not set
11416
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11417
15
{
11418
15
    ImGuiContext& g = *GImGui;
11419
15
    IM_ASSERT(g.NavWindow != NULL);
11420
11421
15
    if (move_flags & ImGuiNavMoveFlags_Tabbing)
11422
0
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
11423
11424
15
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
11425
15
    g.NavMoveDir = move_dir;
11426
15
    g.NavMoveDirForDebug = move_dir;
11427
15
    g.NavMoveClipDir = clip_dir;
11428
15
    g.NavMoveFlags = move_flags;
11429
15
    g.NavMoveScrollFlags = scroll_flags;
11430
15
    g.NavMoveForwardToNextFrame = false;
11431
15
    g.NavMoveKeyMods = g.IO.KeyMods;
11432
15
    g.NavMoveResultLocal.Clear();
11433
15
    g.NavMoveResultLocalVisible.Clear();
11434
15
    g.NavMoveResultOther.Clear();
11435
15
    g.NavTabbingCounter = 0;
11436
15
    g.NavTabbingResultFirst.Clear();
11437
15
    NavUpdateAnyRequestFlag();
11438
15
}
11439
11440
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
11441
0
{
11442
0
    ImGuiContext& g = *GImGui;
11443
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
11444
0
    NavApplyItemToResult(result);
11445
0
    NavUpdateAnyRequestFlag();
11446
0
}
11447
11448
void ImGui::NavMoveRequestCancel()
11449
50
{
11450
50
    ImGuiContext& g = *GImGui;
11451
50
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11452
50
    NavUpdateAnyRequestFlag();
11453
50
}
11454
11455
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
11456
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11457
0
{
11458
0
    ImGuiContext& g = *GImGui;
11459
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
11460
0
    NavMoveRequestCancel();
11461
0
    g.NavMoveForwardToNextFrame = true;
11462
0
    g.NavMoveDir = move_dir;
11463
0
    g.NavMoveClipDir = clip_dir;
11464
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
11465
0
    g.NavMoveScrollFlags = scroll_flags;
11466
0
}
11467
11468
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
11469
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
11470
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
11471
0
{
11472
0
    ImGuiContext& g = *GImGui;
11473
0
    IM_ASSERT(wrap_flags != 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
11474
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test
11475
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
11476
0
        g.NavMoveFlags |= wrap_flags;
11477
0
}
11478
11479
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
11480
// This way we could find the last focused window among our children. It would be much less confusing this way?
11481
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
11482
345
{
11483
345
    ImGuiWindow* parent = nav_window;
11484
532
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
11485
187
        parent = parent->ParentWindow;
11486
345
    if (parent && parent != nav_window)
11487
187
        parent->NavLastChildNavWindow = nav_window;
11488
345
}
11489
11490
// Restore the last focused child.
11491
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
11492
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
11493
3
{
11494
3
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
11495
0
        return window->NavLastChildNavWindow;
11496
3
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
11497
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
11498
0
            return tab->Window;
11499
3
    return window;
11500
3
}
11501
11502
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
11503
3
{
11504
3
    ImGuiContext& g = *GImGui;
11505
3
    if (layer == ImGuiNavLayer_Main)
11506
3
    {
11507
3
        ImGuiWindow* prev_nav_window = g.NavWindow;
11508
3
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
11509
3
        if (prev_nav_window)
11510
3
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
11511
3
    }
11512
3
    ImGuiWindow* window = g.NavWindow;
11513
3
    if (window->NavLastIds[layer] != 0)
11514
3
    {
11515
3
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
11516
3
    }
11517
0
    else
11518
0
    {
11519
0
        g.NavLayer = layer;
11520
0
        NavInitWindow(window, true);
11521
0
    }
11522
3
}
11523
11524
void ImGui::NavRestoreHighlightAfterMove()
11525
1
{
11526
1
    ImGuiContext& g = *GImGui;
11527
1
    g.NavDisableHighlight = false;
11528
1
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
11529
1
}
11530
11531
static inline void ImGui::NavUpdateAnyRequestFlag()
11532
90.4k
{
11533
90.4k
    ImGuiContext& g = *GImGui;
11534
90.4k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
11535
90.4k
    if (g.NavAnyRequest)
11536
90.4k
        IM_ASSERT(g.NavWindow != NULL);
11537
90.4k
}
11538
11539
// This needs to be called before we submit any widget (aka in or before Begin)
11540
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
11541
2
{
11542
    // FIXME: ChildWindow test here is wrong for docking
11543
2
    ImGuiContext& g = *GImGui;
11544
2
    IM_ASSERT(window == g.NavWindow);
11545
11546
2
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
11547
0
    {
11548
0
        g.NavId = 0;
11549
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11550
0
        return;
11551
0
    }
11552
11553
2
    bool init_for_nav = false;
11554
2
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
11555
2
        init_for_nav = true;
11556
2
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
11557
2
    if (init_for_nav)
11558
2
    {
11559
2
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
11560
2
        g.NavInitRequest = true;
11561
2
        g.NavInitRequestFromMove = false;
11562
2
        g.NavInitResultId = 0;
11563
2
        g.NavInitResultRectRel = ImRect();
11564
2
        NavUpdateAnyRequestFlag();
11565
2
    }
11566
0
    else
11567
0
    {
11568
0
        g.NavId = window->NavLastIds[0];
11569
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11570
0
    }
11571
2
}
11572
11573
static ImVec2 ImGui::NavCalcPreferredRefPos()
11574
0
{
11575
0
    ImGuiContext& g = *GImGui;
11576
0
    ImGuiWindow* window = g.NavWindow;
11577
0
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
11578
0
    {
11579
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
11580
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
11581
        // In theory we could move that +1.0f offset in OpenPopupEx()
11582
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
11583
0
        return ImVec2(p.x + 1.0f, p.y);
11584
0
    }
11585
0
    else
11586
0
    {
11587
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
11588
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
11589
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
11590
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
11591
0
        {
11592
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11593
0
            rect_rel.Translate(window->Scroll - next_scroll);
11594
0
        }
11595
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
11596
0
        ImGuiViewport* viewport = window->Viewport;
11597
0
        return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
11598
0
    }
11599
0
}
11600
11601
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
11602
0
{
11603
0
    ImGuiContext& g = *GImGui;
11604
0
    float repeat_delay, repeat_rate;
11605
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
11606
11607
0
    ImGuiKey key_less, key_more;
11608
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
11609
0
    {
11610
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
11611
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
11612
0
    }
11613
0
    else
11614
0
    {
11615
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
11616
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
11617
0
    }
11618
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
11619
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
11620
0
        amount = 0.0f;
11621
0
    return amount;
11622
0
}
11623
11624
static void ImGui::NavUpdate()
11625
90.2k
{
11626
90.2k
    ImGuiContext& g = *GImGui;
11627
90.2k
    ImGuiIO& io = g.IO;
11628
11629
90.2k
    io.WantSetMousePos = false;
11630
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
11631
11632
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
11633
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
11634
90.2k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11635
90.2k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
11636
90.2k
    if (nav_gamepad_active)
11637
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
11638
0
            if (IsKeyDown(key))
11639
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
11640
90.2k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11641
90.2k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
11642
90.2k
    if (nav_keyboard_active)
11643
90.2k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
11644
631k
            if (IsKeyDown(key))
11645
26.0k
                g.NavInputSource = ImGuiInputSource_Keyboard;
11646
11647
    // Process navigation init request (select first/default focus)
11648
90.2k
    if (g.NavInitResultId != 0)
11649
0
        NavInitRequestApplyResult();
11650
90.2k
    g.NavInitRequest = false;
11651
90.2k
    g.NavInitRequestFromMove = false;
11652
90.2k
    g.NavInitResultId = 0;
11653
90.2k
    g.NavJustMovedToId = 0;
11654
11655
    // Process navigation move request
11656
90.2k
    if (g.NavMoveSubmitted)
11657
10
        NavMoveRequestApplyResult();
11658
90.2k
    g.NavTabbingCounter = 0;
11659
90.2k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11660
11661
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
11662
90.2k
    bool set_mouse_pos = false;
11663
90.2k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
11664
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
11665
0
            set_mouse_pos = true;
11666
90.2k
    g.NavMousePosDirty = false;
11667
90.2k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
11668
11669
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
11670
90.2k
    if (g.NavWindow)
11671
345
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
11672
90.2k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
11673
3
        g.NavWindow->NavLastChildNavWindow = NULL;
11674
11675
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
11676
90.2k
    NavUpdateWindowing();
11677
11678
    // Set output flags for user application
11679
90.2k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
11680
90.2k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
11681
11682
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
11683
90.2k
    NavUpdateCancelRequest();
11684
11685
    // Process manual activation request
11686
90.2k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavActivateInputId = 0;
11687
90.2k
    g.NavActivateFlags = ImGuiActivateFlags_None;
11688
90.2k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11689
3
    {
11690
3
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
11691
3
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
11692
3
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
11693
3
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
11694
3
        if (g.ActiveId == 0 && activate_pressed)
11695
0
        {
11696
0
            g.NavActivateId = g.NavId;
11697
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
11698
0
        }
11699
3
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
11700
0
        {
11701
0
            g.NavActivateInputId = g.NavId;
11702
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
11703
0
        }
11704
3
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
11705
0
            g.NavActivateDownId = g.NavId;
11706
3
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
11707
0
            g.NavActivatePressedId = g.NavId;
11708
3
    }
11709
90.2k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11710
0
        g.NavDisableHighlight = true;
11711
90.2k
    if (g.NavActivateId != 0)
11712
90.2k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
11713
11714
    // Process programmatic activation request
11715
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
11716
90.2k
    if (g.NavNextActivateId != 0)
11717
0
    {
11718
0
        if (g.NavNextActivateFlags & ImGuiActivateFlags_PreferInput)
11719
0
            g.NavActivateInputId = g.NavNextActivateId;
11720
0
        else
11721
0
            g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
11722
0
        g.NavActivateFlags = g.NavNextActivateFlags;
11723
0
    }
11724
90.2k
    g.NavNextActivateId = 0;
11725
11726
    // Process move requests
11727
90.2k
    NavUpdateCreateMoveRequest();
11728
90.2k
    if (g.NavMoveDir == ImGuiDir_None)
11729
90.2k
        NavUpdateCreateTabbingRequest();
11730
90.2k
    NavUpdateAnyRequestFlag();
11731
90.2k
    g.NavIdIsAlive = false;
11732
11733
    // Scrolling
11734
90.2k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
11735
345
    {
11736
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
11737
345
        ImGuiWindow* window = g.NavWindow;
11738
345
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
11739
345
        const ImGuiDir move_dir = g.NavMoveDir;
11740
345
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && move_dir != ImGuiDir_None)
11741
1
        {
11742
1
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11743
0
                SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
11744
1
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
11745
1
                SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
11746
1
        }
11747
11748
        // *Normal* Manual scroll with LStick
11749
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
11750
345
        if (nav_gamepad_active)
11751
0
        {
11752
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
11753
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
11754
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
11755
0
                SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
11756
0
            if (scroll_dir.y != 0.0f)
11757
0
                SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
11758
0
        }
11759
345
    }
11760
11761
    // Always prioritize mouse highlight if navigation is disabled
11762
90.2k
    if (!nav_keyboard_active && !nav_gamepad_active)
11763
0
    {
11764
0
        g.NavDisableHighlight = true;
11765
0
        g.NavDisableMouseHover = set_mouse_pos = false;
11766
0
    }
11767
11768
    // Update mouse position if requested
11769
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
11770
90.2k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
11771
0
    {
11772
0
        io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
11773
0
        io.WantSetMousePos = true;
11774
        //IMGUI_DEBUG_LOG_IO("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
11775
0
    }
11776
11777
    // [DEBUG]
11778
90.2k
    g.NavScoringDebugCount = 0;
11779
#if IMGUI_DEBUG_NAV_RECTS
11780
    if (g.NavWindow)
11781
    {
11782
        ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
11783
        if (1) { for (int layer = 0; layer < 2; layer++) { ImRect r = WindowRectRelToAbs(g.NavWindow, g.NavWindow->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255,200,0,255)); } } // [DEBUG]
11784
        if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
11785
    }
11786
#endif
11787
90.2k
}
11788
11789
void ImGui::NavInitRequestApplyResult()
11790
0
{
11791
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
11792
0
    ImGuiContext& g = *GImGui;
11793
0
    if (!g.NavWindow)
11794
0
        return;
11795
11796
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
11797
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
11798
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
11799
0
    SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
11800
0
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
11801
0
    if (g.NavInitRequestFromMove)
11802
0
        NavRestoreHighlightAfterMove();
11803
0
}
11804
11805
void ImGui::NavUpdateCreateMoveRequest()
11806
90.2k
{
11807
90.2k
    ImGuiContext& g = *GImGui;
11808
90.2k
    ImGuiIO& io = g.IO;
11809
90.2k
    ImGuiWindow* window = g.NavWindow;
11810
90.2k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11811
90.2k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11812
11813
90.2k
    if (g.NavMoveForwardToNextFrame && window != NULL)
11814
0
    {
11815
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
11816
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
11817
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
11818
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
11819
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
11820
0
    }
11821
90.2k
    else
11822
90.2k
    {
11823
        // Initiate directional inputs request
11824
90.2k
        g.NavMoveDir = ImGuiDir_None;
11825
90.2k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
11826
90.2k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
11827
90.2k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
11828
345
        {
11829
345
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
11830
345
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
11831
345
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
11832
345
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
11833
345
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
11834
345
        }
11835
90.2k
        g.NavMoveClipDir = g.NavMoveDir;
11836
90.2k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
11837
90.2k
    }
11838
11839
    // Update PageUp/PageDown/Home/End scroll
11840
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
11841
90.2k
    float scoring_rect_offset_y = 0.0f;
11842
90.2k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
11843
333
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
11844
90.2k
    if (scoring_rect_offset_y != 0.0f)
11845
3
    {
11846
3
        g.NavScoringNoClipRect = window->InnerRect;
11847
3
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
11848
3
    }
11849
11850
    // [DEBUG] Always send a request
11851
#if IMGUI_DEBUG_NAV_SCORING
11852
    if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
11853
        g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
11854
    if (io.KeyCtrl && g.NavMoveDir == ImGuiDir_None)
11855
    {
11856
        g.NavMoveDir = g.NavMoveDirForDebug;
11857
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
11858
    }
11859
#endif
11860
11861
    // Submit
11862
90.2k
    g.NavMoveForwardToNextFrame = false;
11863
90.2k
    if (g.NavMoveDir != ImGuiDir_None)
11864
15
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
11865
11866
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
11867
90.2k
    if (g.NavMoveSubmitted && g.NavId == 0)
11868
12
    {
11869
12
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
11870
12
        g.NavInitRequest = g.NavInitRequestFromMove = true;
11871
12
        g.NavInitResultId = 0;
11872
12
        g.NavDisableHighlight = false;
11873
12
    }
11874
11875
    // When using gamepad, we project the reference nav bounding box into window visible area.
11876
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad all movements are relative
11877
    // (can't focus a visible object like we can with the mouse).
11878
90.2k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
11879
0
    {
11880
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
11881
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
11882
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
11883
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
11884
0
        {
11885
            //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
11886
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
11887
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
11888
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
11889
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
11890
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
11891
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
11892
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
11893
0
            g.NavId = 0;
11894
0
        }
11895
0
    }
11896
11897
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
11898
90.2k
    ImRect scoring_rect;
11899
90.2k
    if (window != NULL)
11900
345
    {
11901
345
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
11902
345
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
11903
345
        scoring_rect.TranslateY(scoring_rect_offset_y);
11904
345
        scoring_rect.Min.x = ImMin(scoring_rect.Min.x + 1.0f, scoring_rect.Max.x);
11905
345
        scoring_rect.Max.x = scoring_rect.Min.x;
11906
345
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
11907
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
11908
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
11909
345
    }
11910
90.2k
    g.NavScoringRect = scoring_rect;
11911
90.2k
    g.NavScoringNoClipRect.Add(scoring_rect);
11912
90.2k
}
11913
11914
void ImGui::NavUpdateCreateTabbingRequest()
11915
90.2k
{
11916
90.2k
    ImGuiContext& g = *GImGui;
11917
90.2k
    ImGuiWindow* window = g.NavWindow;
11918
90.2k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
11919
90.2k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
11920
89.8k
        return;
11921
11922
330
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
11923
330
    if (!tab_pressed)
11924
330
        return;
11925
11926
    // Initiate tabbing request
11927
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
11928
    // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.
11929
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
11930
    //// FIXME: We use (g.ActiveId == 0) but (g.NavDisableHighlight == false) might be righter once we can tab through anything
11931
0
    g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
11932
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
11933
0
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
11934
0
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
11935
0
    g.NavTabbingCounter = -1;
11936
0
}
11937
11938
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
11939
void ImGui::NavMoveRequestApplyResult()
11940
10
{
11941
10
    ImGuiContext& g = *GImGui;
11942
#if IMGUI_DEBUG_NAV_SCORING
11943
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
11944
        return;
11945
#endif
11946
11947
    // Select which result to use
11948
10
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
11949
11950
    // Tabbing forward wrap
11951
10
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
11952
0
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
11953
0
            result = &g.NavTabbingResultFirst;
11954
11955
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
11956
10
    if (result == NULL)
11957
10
    {
11958
10
        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
11959
0
            g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
11960
10
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
11961
0
            NavRestoreHighlightAfterMove();
11962
10
        return;
11963
10
    }
11964
11965
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
11966
0
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
11967
0
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
11968
0
            result = &g.NavMoveResultLocalVisible;
11969
11970
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
11971
0
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
11972
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
11973
0
            result = &g.NavMoveResultOther;
11974
0
    IM_ASSERT(g.NavWindow && result->Window);
11975
11976
    // Scroll to keep newly navigated item fully into view.
11977
0
    if (g.NavLayer == ImGuiNavLayer_Main)
11978
0
    {
11979
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
11980
0
        {
11981
            // FIXME: Should remove this
11982
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
11983
0
            SetScrollY(result->Window, scroll_target);
11984
0
        }
11985
0
        else
11986
0
        {
11987
0
            ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
11988
0
            ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
11989
0
        }
11990
0
    }
11991
11992
0
    if (g.NavWindow != result->Window)
11993
0
    {
11994
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
11995
0
        g.NavWindow = result->Window;
11996
0
    }
11997
0
    if (g.ActiveId != result->ID)
11998
0
        ClearActiveID();
11999
0
    if (g.NavId != result->ID)
12000
0
    {
12001
        // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12002
0
        g.NavJustMovedToId = result->ID;
12003
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12004
0
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12005
0
    }
12006
12007
    // Focus
12008
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12009
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12010
12011
    // Tabbing: Activates Inputable or Focus non-Inputable
12012
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable))
12013
0
    {
12014
0
        g.NavNextActivateId = result->ID;
12015
0
        g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
12016
0
        g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
12017
0
    }
12018
12019
    // Activate
12020
0
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12021
0
    {
12022
0
        g.NavNextActivateId = result->ID;
12023
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12024
0
    }
12025
12026
    // Enable nav highlight
12027
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
12028
0
        NavRestoreHighlightAfterMove();
12029
0
}
12030
12031
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12032
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12033
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12034
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12035
static void ImGui::NavUpdateCancelRequest()
12036
90.2k
{
12037
90.2k
    ImGuiContext& g = *GImGui;
12038
90.2k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12039
90.2k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12040
90.2k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12041
89.6k
        return;
12042
12043
541
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12044
541
    if (g.ActiveId != 0)
12045
0
    {
12046
0
        ClearActiveID();
12047
0
    }
12048
541
    else if (g.NavLayer != ImGuiNavLayer_Main)
12049
0
    {
12050
        // Leave the "menu" layer
12051
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12052
0
        NavRestoreHighlightAfterMove();
12053
0
    }
12054
541
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12055
1
    {
12056
        // Exit child window
12057
1
        ImGuiWindow* child_window = g.NavWindow;
12058
1
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12059
1
        IM_ASSERT(child_window->ChildId != 0);
12060
1
        ImRect child_rect = child_window->Rect();
12061
1
        FocusWindow(parent_window);
12062
1
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12063
1
        NavRestoreHighlightAfterMove();
12064
1
    }
12065
540
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12066
0
    {
12067
        // Close open popup/menu
12068
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12069
0
    }
12070
540
    else
12071
540
    {
12072
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12073
540
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12074
0
            g.NavWindow->NavLastIds[0] = 0;
12075
540
        g.NavId = 0;
12076
540
    }
12077
541
}
12078
12079
// Handle PageUp/PageDown/Home/End keys
12080
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12081
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12082
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12083
static float ImGui::NavUpdatePageUpPageDown()
12084
333
{
12085
333
    ImGuiContext& g = *GImGui;
12086
333
    ImGuiWindow* window = g.NavWindow;
12087
333
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12088
0
        return 0.0f;
12089
12090
333
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12091
333
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12092
333
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12093
333
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12094
333
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12095
318
        return 0.0f;
12096
12097
15
    if (g.NavLayer != ImGuiNavLayer_Main)
12098
3
        NavRestoreLayer(ImGuiNavLayer_Main);
12099
12100
15
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)
12101
1
    {
12102
        // Fallback manual-scroll when window has no navigable item
12103
1
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12104
0
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12105
1
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12106
0
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12107
1
        else if (home_pressed)
12108
0
            SetScrollY(window, 0.0f);
12109
1
        else if (end_pressed)
12110
0
            SetScrollY(window, window->ScrollMax.y);
12111
1
    }
12112
14
    else
12113
14
    {
12114
14
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12115
14
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12116
14
        float nav_scoring_rect_offset_y = 0.0f;
12117
14
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12118
0
        {
12119
0
            nav_scoring_rect_offset_y = -page_offset_y;
12120
0
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12121
0
            g.NavMoveClipDir = ImGuiDir_Up;
12122
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12123
0
        }
12124
14
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12125
3
        {
12126
3
            nav_scoring_rect_offset_y = +page_offset_y;
12127
3
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12128
3
            g.NavMoveClipDir = ImGuiDir_Down;
12129
3
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12130
3
        }
12131
11
        else if (home_pressed)
12132
0
        {
12133
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12134
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12135
            // Preserve current horizontal position if we have any.
12136
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12137
0
            if (nav_rect_rel.IsInverted())
12138
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12139
0
            g.NavMoveDir = ImGuiDir_Down;
12140
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12141
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12142
0
        }
12143
11
        else if (end_pressed)
12144
0
        {
12145
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12146
0
            if (nav_rect_rel.IsInverted())
12147
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12148
0
            g.NavMoveDir = ImGuiDir_Up;
12149
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12150
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12151
0
        }
12152
14
        return nav_scoring_rect_offset_y;
12153
14
    }
12154
1
    return 0.0f;
12155
15
}
12156
12157
static void ImGui::NavEndFrame()
12158
90.2k
{
12159
90.2k
    ImGuiContext& g = *GImGui;
12160
12161
    // Show CTRL+TAB list window
12162
90.2k
    if (g.NavWindowingTarget != NULL)
12163
0
        NavUpdateWindowingOverlay();
12164
12165
    // Perform wrap-around in menus
12166
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12167
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12168
90.2k
    const ImGuiNavMoveFlags wanted_flags = ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY;
12169
90.2k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & wanted_flags) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12170
0
        NavUpdateCreateWrappingRequest();
12171
90.2k
}
12172
12173
static void ImGui::NavUpdateCreateWrappingRequest()
12174
0
{
12175
0
    ImGuiContext& g = *GImGui;
12176
0
    ImGuiWindow* window = g.NavWindow;
12177
12178
0
    bool do_forward = false;
12179
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12180
0
    ImGuiDir clip_dir = g.NavMoveDir;
12181
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12182
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12183
0
    {
12184
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12185
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12186
0
        {
12187
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12188
0
            clip_dir = ImGuiDir_Up;
12189
0
        }
12190
0
        do_forward = true;
12191
0
    }
12192
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12193
0
    {
12194
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12195
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12196
0
        {
12197
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12198
0
            clip_dir = ImGuiDir_Down;
12199
0
        }
12200
0
        do_forward = true;
12201
0
    }
12202
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12203
0
    {
12204
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12205
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12206
0
        {
12207
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12208
0
            clip_dir = ImGuiDir_Left;
12209
0
        }
12210
0
        do_forward = true;
12211
0
    }
12212
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12213
0
    {
12214
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12215
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12216
0
        {
12217
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12218
0
            clip_dir = ImGuiDir_Right;
12219
0
        }
12220
0
        do_forward = true;
12221
0
    }
12222
0
    if (!do_forward)
12223
0
        return;
12224
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12225
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12226
0
}
12227
12228
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12229
0
{
12230
0
    ImGuiContext& g = *GImGui;
12231
0
    IM_UNUSED(g);
12232
0
    int order = window->FocusOrder;
12233
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12234
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12235
0
    return order;
12236
0
}
12237
12238
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12239
0
{
12240
0
    ImGuiContext& g = *GImGui;
12241
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12242
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12243
0
            return g.WindowsFocusOrder[i];
12244
0
    return NULL;
12245
0
}
12246
12247
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12248
0
{
12249
0
    ImGuiContext& g = *GImGui;
12250
0
    IM_ASSERT(g.NavWindowingTarget);
12251
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12252
0
        return;
12253
12254
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12255
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12256
0
    if (!window_target)
12257
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12258
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12259
0
    {
12260
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12261
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12262
0
    }
12263
0
    g.NavWindowingToggleLayer = false;
12264
0
}
12265
12266
// Windowing management mode
12267
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12268
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12269
static void ImGui::NavUpdateWindowing()
12270
90.2k
{
12271
90.2k
    ImGuiContext& g = *GImGui;
12272
90.2k
    ImGuiIO& io = g.IO;
12273
12274
90.2k
    ImGuiWindow* apply_focus_window = NULL;
12275
90.2k
    bool apply_toggle_layer = false;
12276
12277
90.2k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12278
90.2k
    bool allow_windowing = (modal_window == NULL);
12279
90.2k
    if (!allow_windowing)
12280
0
        g.NavWindowingTarget = NULL;
12281
12282
    // Fade out
12283
90.2k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12284
0
    {
12285
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12286
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12287
0
            g.NavWindowingTargetAnim = NULL;
12288
0
    }
12289
12290
    // Start CTRL+Tab or Square+L/R window selection
12291
90.2k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12292
90.2k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12293
90.2k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12294
90.2k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12295
90.2k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12296
90.2k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12297
90.2k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12298
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12299
0
        {
12300
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12301
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12302
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12303
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
12304
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
12305
0
        }
12306
12307
    // Gamepad update
12308
90.2k
    g.NavWindowingTimer += io.DeltaTime;
12309
90.2k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
12310
0
    {
12311
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
12312
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
12313
12314
        // Select window to focus
12315
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
12316
0
        if (focus_change_dir != 0)
12317
0
        {
12318
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
12319
0
            g.NavWindowingHighlightAlpha = 1.0f;
12320
0
        }
12321
12322
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
12323
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
12324
0
        {
12325
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
12326
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
12327
0
                apply_toggle_layer = true;
12328
0
            else if (!g.NavWindowingToggleLayer)
12329
0
                apply_focus_window = g.NavWindowingTarget;
12330
0
            g.NavWindowingTarget = NULL;
12331
0
        }
12332
0
    }
12333
12334
    // Keyboard: Focus
12335
90.2k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
12336
0
    {
12337
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
12338
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
12339
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
12340
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
12341
0
        if (keyboard_next_window || keyboard_prev_window)
12342
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
12343
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
12344
0
            apply_focus_window = g.NavWindowingTarget;
12345
0
    }
12346
12347
    // Keyboard: Press and Release ALT to toggle menu layer
12348
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
12349
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
12350
90.2k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
12351
0
    {
12352
0
        g.NavWindowingToggleLayer = true;
12353
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
12354
0
    }
12355
90.2k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
12356
0
    {
12357
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
12358
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
12359
        // We cancel toggling nav layer if an owner has claimed the key.
12360
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
12361
0
            g.NavWindowingToggleLayer = false;
12362
12363
        // Apply layer toggle on release
12364
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
12365
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
12366
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
12367
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
12368
0
                    apply_toggle_layer = true;
12369
0
        if (!IsKeyDown(ImGuiMod_Alt))
12370
0
            g.NavWindowingToggleLayer = false;
12371
0
    }
12372
12373
    // Move window
12374
90.2k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
12375
0
    {
12376
0
        ImVec2 nav_move_dir;
12377
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
12378
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
12379
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
12380
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12381
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
12382
0
        {
12383
0
            const float NAV_MOVE_SPEED = 800.0f;
12384
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
12385
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
12386
0
            g.NavDisableMouseHover = true;
12387
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaPos);
12388
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
12389
0
            {
12390
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
12391
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
12392
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
12393
0
            }
12394
0
        }
12395
0
    }
12396
12397
    // Apply final focus
12398
90.2k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
12399
0
    {
12400
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
12401
0
        ClearActiveID();
12402
0
        NavRestoreHighlightAfterMove();
12403
0
        apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
12404
0
        ClosePopupsOverWindow(apply_focus_window, false);
12405
0
        FocusWindow(apply_focus_window);
12406
0
        if (apply_focus_window->NavLastIds[0] == 0)
12407
0
            NavInitWindow(apply_focus_window, false);
12408
12409
        // If the window has ONLY a menu layer (no main layer), select it directly
12410
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
12411
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
12412
        // the target window as already been previewed once.
12413
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
12414
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
12415
        // won't be valid.
12416
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
12417
0
            g.NavLayer = ImGuiNavLayer_Menu;
12418
12419
        // Request OS level focus
12420
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
12421
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
12422
0
    }
12423
90.2k
    if (apply_focus_window)
12424
0
        g.NavWindowingTarget = NULL;
12425
12426
    // Apply menu/layer toggle
12427
90.2k
    if (apply_toggle_layer && g.NavWindow)
12428
0
    {
12429
0
        ClearActiveID();
12430
12431
        // Move to parent menu if necessary
12432
0
        ImGuiWindow* new_nav_window = g.NavWindow;
12433
0
        while (new_nav_window->ParentWindow
12434
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
12435
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
12436
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12437
0
            new_nav_window = new_nav_window->ParentWindow;
12438
0
        if (new_nav_window != g.NavWindow)
12439
0
        {
12440
0
            ImGuiWindow* old_nav_window = g.NavWindow;
12441
0
            FocusWindow(new_nav_window);
12442
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
12443
0
        }
12444
12445
        // Toggle layer
12446
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
12447
0
        if (new_nav_layer != g.NavLayer)
12448
0
        {
12449
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
12450
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
12451
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
12452
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
12453
0
            NavRestoreLayer(new_nav_layer);
12454
0
            NavRestoreHighlightAfterMove();
12455
0
        }
12456
0
    }
12457
90.2k
}
12458
12459
// Window has already passed the IsWindowNavFocusable()
12460
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
12461
0
{
12462
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12463
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
12464
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
12465
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
12466
0
    if (window->DockNodeAsHost)
12467
0
        return "(Dock node)"; // Not normally shown to user.
12468
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
12469
0
}
12470
12471
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
12472
void ImGui::NavUpdateWindowingOverlay()
12473
0
{
12474
0
    ImGuiContext& g = *GImGui;
12475
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
12476
12477
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
12478
0
        return;
12479
12480
0
    if (g.NavWindowingListWindow == NULL)
12481
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
12482
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
12483
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
12484
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
12485
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
12486
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
12487
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
12488
0
    {
12489
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
12490
0
        IM_ASSERT(window != NULL); // Fix static analyzers
12491
0
        if (!IsWindowNavFocusable(window))
12492
0
            continue;
12493
0
        const char* label = window->Name;
12494
0
        if (label == FindRenderedTextEnd(label))
12495
0
            label = GetFallbackWindowNameForWindowingList(window);
12496
0
        Selectable(label, g.NavWindowingTarget == window);
12497
0
    }
12498
0
    End();
12499
0
    PopStyleVar();
12500
0
}
12501
12502
12503
//-----------------------------------------------------------------------------
12504
// [SECTION] DRAG AND DROP
12505
//-----------------------------------------------------------------------------
12506
12507
bool ImGui::IsDragDropActive()
12508
0
{
12509
0
    ImGuiContext& g = *GImGui;
12510
0
    return g.DragDropActive;
12511
0
}
12512
12513
void ImGui::ClearDragDrop()
12514
12
{
12515
12
    ImGuiContext& g = *GImGui;
12516
12
    g.DragDropActive = false;
12517
12
    g.DragDropPayload.Clear();
12518
12
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
12519
12
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
12520
12
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
12521
12
    g.DragDropAcceptFrameCount = -1;
12522
12523
12
    g.DragDropPayloadBufHeap.clear();
12524
12
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12525
12
}
12526
12527
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
12528
// If the item has an identifier:
12529
// - This assume/require the item to be activated (typically via ButtonBehavior).
12530
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
12531
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
12532
// If the item has no identifier:
12533
// - Currently always assume left mouse button.
12534
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
12535
43
{
12536
43
    ImGuiContext& g = *GImGui;
12537
43
    ImGuiWindow* window = g.CurrentWindow;
12538
12539
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
12540
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
12541
43
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
12542
12543
43
    bool source_drag_active = false;
12544
43
    ImGuiID source_id = 0;
12545
43
    ImGuiID source_parent_id = 0;
12546
43
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
12547
43
    {
12548
43
        source_id = g.LastItemData.ID;
12549
43
        if (source_id != 0)
12550
43
        {
12551
            // Common path: items with ID
12552
43
            if (g.ActiveId != source_id)
12553
0
                return false;
12554
43
            if (g.ActiveIdMouseButton != -1)
12555
0
                mouse_button = g.ActiveIdMouseButton;
12556
43
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12557
0
                return false;
12558
43
            g.ActiveIdAllowOverlap = false;
12559
43
        }
12560
0
        else
12561
0
        {
12562
            // Uncommon path: items without ID
12563
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12564
0
                return false;
12565
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
12566
0
                return false;
12567
12568
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
12569
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
12570
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
12571
0
            {
12572
0
                IM_ASSERT(0);
12573
0
                return false;
12574
0
            }
12575
12576
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
12577
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
12578
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
12579
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
12580
            // Rely on keeping other window->LastItemXXX fields intact.
12581
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
12582
0
            KeepAliveID(source_id);
12583
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);
12584
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
12585
0
            {
12586
0
                SetActiveID(source_id, window);
12587
0
                FocusWindow(window);
12588
0
            }
12589
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
12590
0
                g.ActiveIdAllowOverlap = is_hovered;
12591
0
        }
12592
43
        if (g.ActiveId != source_id)
12593
0
            return false;
12594
43
        source_parent_id = window->IDStack.back();
12595
43
        source_drag_active = IsMouseDragging(mouse_button);
12596
12597
        // Disable navigation and key inputs while dragging + cancel existing request if any
12598
43
        SetActiveIdUsingAllKeyboardKeys();
12599
43
    }
12600
0
    else
12601
0
    {
12602
0
        window = NULL;
12603
0
        source_id = ImHashStr("#SourceExtern");
12604
0
        source_drag_active = true;
12605
0
    }
12606
12607
43
    if (source_drag_active)
12608
40
    {
12609
40
        if (!g.DragDropActive)
12610
6
        {
12611
6
            IM_ASSERT(source_id != 0);
12612
6
            ClearDragDrop();
12613
6
            ImGuiPayload& payload = g.DragDropPayload;
12614
6
            payload.SourceId = source_id;
12615
6
            payload.SourceParentId = source_parent_id;
12616
6
            g.DragDropActive = true;
12617
6
            g.DragDropSourceFlags = flags;
12618
6
            g.DragDropMouseButton = mouse_button;
12619
6
            if (payload.SourceId == g.ActiveId)
12620
6
                g.ActiveIdNoClearOnFocusLoss = true;
12621
6
        }
12622
40
        g.DragDropSourceFrameCount = g.FrameCount;
12623
40
        g.DragDropWithinSource = true;
12624
12625
40
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12626
0
        {
12627
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
12628
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
12629
0
            BeginTooltip();
12630
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
12631
0
            {
12632
0
                ImGuiWindow* tooltip_window = g.CurrentWindow;
12633
0
                tooltip_window->Hidden = tooltip_window->SkipItems = true;
12634
0
                tooltip_window->HiddenFramesCanSkipItems = 1;
12635
0
            }
12636
0
        }
12637
12638
40
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
12639
40
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
12640
12641
40
        return true;
12642
40
    }
12643
3
    return false;
12644
43
}
12645
12646
void ImGui::EndDragDropSource()
12647
40
{
12648
40
    ImGuiContext& g = *GImGui;
12649
40
    IM_ASSERT(g.DragDropActive);
12650
40
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
12651
12652
40
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12653
0
        EndTooltip();
12654
12655
    // Discard the drag if have not called SetDragDropPayload()
12656
40
    if (g.DragDropPayload.DataFrameCount == -1)
12657
0
        ClearDragDrop();
12658
40
    g.DragDropWithinSource = false;
12659
40
}
12660
12661
// Use 'cond' to choose to submit payload on drag start or every frame
12662
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
12663
40
{
12664
40
    ImGuiContext& g = *GImGui;
12665
40
    ImGuiPayload& payload = g.DragDropPayload;
12666
40
    if (cond == 0)
12667
40
        cond = ImGuiCond_Always;
12668
12669
40
    IM_ASSERT(type != NULL);
12670
40
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
12671
40
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
12672
40
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
12673
40
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
12674
12675
40
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
12676
40
    {
12677
        // Copy payload
12678
40
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
12679
40
        g.DragDropPayloadBufHeap.resize(0);
12680
40
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
12681
0
        {
12682
            // Store in heap
12683
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
12684
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
12685
0
            memcpy(payload.Data, data, data_size);
12686
0
        }
12687
40
        else if (data_size > 0)
12688
40
        {
12689
            // Store locally
12690
40
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12691
40
            payload.Data = g.DragDropPayloadBufLocal;
12692
40
            memcpy(payload.Data, data, data_size);
12693
40
        }
12694
0
        else
12695
0
        {
12696
0
            payload.Data = NULL;
12697
0
        }
12698
40
        payload.DataSize = (int)data_size;
12699
40
    }
12700
40
    payload.DataFrameCount = g.FrameCount;
12701
12702
    // Return whether the payload has been accepted
12703
40
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
12704
40
}
12705
12706
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
12707
60
{
12708
60
    ImGuiContext& g = *GImGui;
12709
60
    if (!g.DragDropActive)
12710
0
        return false;
12711
12712
60
    ImGuiWindow* window = g.CurrentWindow;
12713
60
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12714
60
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
12715
60
        return false;
12716
0
    IM_ASSERT(id != 0);
12717
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
12718
0
        return false;
12719
0
    if (window->SkipItems)
12720
0
        return false;
12721
12722
0
    IM_ASSERT(g.DragDropWithinTarget == false);
12723
0
    g.DragDropTargetRect = bb;
12724
0
    g.DragDropTargetId = id;
12725
0
    g.DragDropWithinTarget = true;
12726
0
    return true;
12727
0
}
12728
12729
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
12730
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
12731
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
12732
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
12733
bool ImGui::BeginDragDropTarget()
12734
0
{
12735
0
    ImGuiContext& g = *GImGui;
12736
0
    if (!g.DragDropActive)
12737
0
        return false;
12738
12739
0
    ImGuiWindow* window = g.CurrentWindow;
12740
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
12741
0
        return false;
12742
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12743
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
12744
0
        return false;
12745
12746
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
12747
0
    ImGuiID id = g.LastItemData.ID;
12748
0
    if (id == 0)
12749
0
    {
12750
0
        id = window->GetIDFromRectangle(display_rect);
12751
0
        KeepAliveID(id);
12752
0
    }
12753
0
    if (g.DragDropPayload.SourceId == id)
12754
0
        return false;
12755
12756
0
    IM_ASSERT(g.DragDropWithinTarget == false);
12757
0
    g.DragDropTargetRect = display_rect;
12758
0
    g.DragDropTargetId = id;
12759
0
    g.DragDropWithinTarget = true;
12760
0
    return true;
12761
0
}
12762
12763
bool ImGui::IsDragDropPayloadBeingAccepted()
12764
7
{
12765
7
    ImGuiContext& g = *GImGui;
12766
7
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
12767
7
}
12768
12769
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
12770
0
{
12771
0
    ImGuiContext& g = *GImGui;
12772
0
    ImGuiWindow* window = g.CurrentWindow;
12773
0
    ImGuiPayload& payload = g.DragDropPayload;
12774
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
12775
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
12776
0
    if (type != NULL && !payload.IsDataType(type))
12777
0
        return NULL;
12778
12779
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
12780
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
12781
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
12782
0
    ImRect r = g.DragDropTargetRect;
12783
0
    float r_surface = r.GetWidth() * r.GetHeight();
12784
0
    if (r_surface <= g.DragDropAcceptIdCurrRectSurface)
12785
0
    {
12786
0
        g.DragDropAcceptFlags = flags;
12787
0
        g.DragDropAcceptIdCurr = g.DragDropTargetId;
12788
0
        g.DragDropAcceptIdCurrRectSurface = r_surface;
12789
0
    }
12790
12791
    // Render default drop visuals
12792
0
    payload.Preview = was_accepted_previously;
12793
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
12794
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
12795
0
        window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
12796
12797
0
    g.DragDropAcceptFrameCount = g.FrameCount;
12798
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
12799
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
12800
0
        return NULL;
12801
12802
0
    return &payload;
12803
0
}
12804
12805
// FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
12806
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
12807
0
{
12808
0
    GetWindowDrawList()->AddRect(bb.Min - ImVec2(3.5f, 3.5f), bb.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
12809
0
}
12810
12811
const ImGuiPayload* ImGui::GetDragDropPayload()
12812
0
{
12813
0
    ImGuiContext& g = *GImGui;
12814
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
12815
0
}
12816
12817
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
12818
void ImGui::EndDragDropTarget()
12819
0
{
12820
0
    ImGuiContext& g = *GImGui;
12821
0
    IM_ASSERT(g.DragDropActive);
12822
0
    IM_ASSERT(g.DragDropWithinTarget);
12823
0
    g.DragDropWithinTarget = false;
12824
0
}
12825
12826
//-----------------------------------------------------------------------------
12827
// [SECTION] LOGGING/CAPTURING
12828
//-----------------------------------------------------------------------------
12829
// All text output from the interface can be captured into tty/file/clipboard.
12830
// By default, tree nodes are automatically opened during logging.
12831
//-----------------------------------------------------------------------------
12832
12833
// Pass text data straight to log (without being displayed)
12834
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
12835
0
{
12836
0
    if (g.LogFile)
12837
0
    {
12838
0
        g.LogBuffer.Buf.resize(0);
12839
0
        g.LogBuffer.appendfv(fmt, args);
12840
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
12841
0
    }
12842
0
    else
12843
0
    {
12844
0
        g.LogBuffer.appendfv(fmt, args);
12845
0
    }
12846
0
}
12847
12848
void ImGui::LogText(const char* fmt, ...)
12849
0
{
12850
0
    ImGuiContext& g = *GImGui;
12851
0
    if (!g.LogEnabled)
12852
0
        return;
12853
12854
0
    va_list args;
12855
0
    va_start(args, fmt);
12856
0
    LogTextV(g, fmt, args);
12857
0
    va_end(args);
12858
0
}
12859
12860
void ImGui::LogTextV(const char* fmt, va_list args)
12861
0
{
12862
0
    ImGuiContext& g = *GImGui;
12863
0
    if (!g.LogEnabled)
12864
0
        return;
12865
12866
0
    LogTextV(g, fmt, args);
12867
0
}
12868
12869
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
12870
// We split text into individual lines to add current tree level padding
12871
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
12872
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
12873
0
{
12874
0
    ImGuiContext& g = *GImGui;
12875
0
    ImGuiWindow* window = g.CurrentWindow;
12876
12877
0
    const char* prefix = g.LogNextPrefix;
12878
0
    const char* suffix = g.LogNextSuffix;
12879
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
12880
12881
0
    if (!text_end)
12882
0
        text_end = FindRenderedTextEnd(text, text_end);
12883
12884
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
12885
0
    if (ref_pos)
12886
0
        g.LogLinePosY = ref_pos->y;
12887
0
    if (log_new_line)
12888
0
    {
12889
0
        LogText(IM_NEWLINE);
12890
0
        g.LogLineFirstItem = true;
12891
0
    }
12892
12893
0
    if (prefix)
12894
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
12895
12896
    // Re-adjust padding if we have popped out of our starting depth
12897
0
    if (g.LogDepthRef > window->DC.TreeDepth)
12898
0
        g.LogDepthRef = window->DC.TreeDepth;
12899
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
12900
12901
0
    const char* text_remaining = text;
12902
0
    for (;;)
12903
0
    {
12904
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
12905
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
12906
0
        const char* line_start = text_remaining;
12907
0
        const char* line_end = ImStreolRange(line_start, text_end);
12908
0
        const bool is_last_line = (line_end == text_end);
12909
0
        if (line_start != line_end || !is_last_line)
12910
0
        {
12911
0
            const int line_length = (int)(line_end - line_start);
12912
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
12913
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
12914
0
            g.LogLineFirstItem = false;
12915
0
            if (*line_end == '\n')
12916
0
            {
12917
0
                LogText(IM_NEWLINE);
12918
0
                g.LogLineFirstItem = true;
12919
0
            }
12920
0
        }
12921
0
        if (is_last_line)
12922
0
            break;
12923
0
        text_remaining = line_end + 1;
12924
0
    }
12925
12926
0
    if (suffix)
12927
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
12928
0
}
12929
12930
// Start logging/capturing text output
12931
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
12932
0
{
12933
0
    ImGuiContext& g = *GImGui;
12934
0
    ImGuiWindow* window = g.CurrentWindow;
12935
0
    IM_ASSERT(g.LogEnabled == false);
12936
0
    IM_ASSERT(g.LogFile == NULL);
12937
0
    IM_ASSERT(g.LogBuffer.empty());
12938
0
    g.LogEnabled = true;
12939
0
    g.LogType = type;
12940
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
12941
0
    g.LogDepthRef = window->DC.TreeDepth;
12942
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
12943
0
    g.LogLinePosY = FLT_MAX;
12944
0
    g.LogLineFirstItem = true;
12945
0
}
12946
12947
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
12948
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
12949
0
{
12950
0
    ImGuiContext& g = *GImGui;
12951
0
    g.LogNextPrefix = prefix;
12952
0
    g.LogNextSuffix = suffix;
12953
0
}
12954
12955
void ImGui::LogToTTY(int auto_open_depth)
12956
0
{
12957
0
    ImGuiContext& g = *GImGui;
12958
0
    if (g.LogEnabled)
12959
0
        return;
12960
0
    IM_UNUSED(auto_open_depth);
12961
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
12962
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
12963
0
    g.LogFile = stdout;
12964
0
#endif
12965
0
}
12966
12967
// Start logging/capturing text output to given file
12968
void ImGui::LogToFile(int auto_open_depth, const char* filename)
12969
0
{
12970
0
    ImGuiContext& g = *GImGui;
12971
0
    if (g.LogEnabled)
12972
0
        return;
12973
12974
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
12975
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
12976
    // By opening the file in binary mode "ab" we have consistent output everywhere.
12977
0
    if (!filename)
12978
0
        filename = g.IO.LogFilename;
12979
0
    if (!filename || !filename[0])
12980
0
        return;
12981
0
    ImFileHandle f = ImFileOpen(filename, "ab");
12982
0
    if (!f)
12983
0
    {
12984
0
        IM_ASSERT(0);
12985
0
        return;
12986
0
    }
12987
12988
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
12989
0
    g.LogFile = f;
12990
0
}
12991
12992
// Start logging/capturing text output to clipboard
12993
void ImGui::LogToClipboard(int auto_open_depth)
12994
0
{
12995
0
    ImGuiContext& g = *GImGui;
12996
0
    if (g.LogEnabled)
12997
0
        return;
12998
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
12999
0
}
13000
13001
void ImGui::LogToBuffer(int auto_open_depth)
13002
0
{
13003
0
    ImGuiContext& g = *GImGui;
13004
0
    if (g.LogEnabled)
13005
0
        return;
13006
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13007
0
}
13008
13009
void ImGui::LogFinish()
13010
180k
{
13011
180k
    ImGuiContext& g = *GImGui;
13012
180k
    if (!g.LogEnabled)
13013
180k
        return;
13014
13015
0
    LogText(IM_NEWLINE);
13016
0
    switch (g.LogType)
13017
0
    {
13018
0
    case ImGuiLogType_TTY:
13019
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13020
0
        fflush(g.LogFile);
13021
0
#endif
13022
0
        break;
13023
0
    case ImGuiLogType_File:
13024
0
        ImFileClose(g.LogFile);
13025
0
        break;
13026
0
    case ImGuiLogType_Buffer:
13027
0
        break;
13028
0
    case ImGuiLogType_Clipboard:
13029
0
        if (!g.LogBuffer.empty())
13030
0
            SetClipboardText(g.LogBuffer.begin());
13031
0
        break;
13032
0
    case ImGuiLogType_None:
13033
0
        IM_ASSERT(0);
13034
0
        break;
13035
0
    }
13036
13037
0
    g.LogEnabled = false;
13038
0
    g.LogType = ImGuiLogType_None;
13039
0
    g.LogFile = NULL;
13040
0
    g.LogBuffer.clear();
13041
0
}
13042
13043
// Helper to display logging buttons
13044
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13045
void ImGui::LogButtons()
13046
0
{
13047
0
    ImGuiContext& g = *GImGui;
13048
13049
0
    PushID("LogButtons");
13050
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13051
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13052
#else
13053
    const bool log_to_tty = false;
13054
#endif
13055
0
    const bool log_to_file = Button("Log To File"); SameLine();
13056
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13057
0
    PushAllowKeyboardFocus(false);
13058
0
    SetNextItemWidth(80.0f);
13059
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13060
0
    PopAllowKeyboardFocus();
13061
0
    PopID();
13062
13063
    // Start logging at the end of the function so that the buttons don't appear in the log
13064
0
    if (log_to_tty)
13065
0
        LogToTTY();
13066
0
    if (log_to_file)
13067
0
        LogToFile();
13068
0
    if (log_to_clipboard)
13069
0
        LogToClipboard();
13070
0
}
13071
13072
13073
//-----------------------------------------------------------------------------
13074
// [SECTION] SETTINGS
13075
//-----------------------------------------------------------------------------
13076
// - UpdateSettings() [Internal]
13077
// - MarkIniSettingsDirty() [Internal]
13078
// - CreateNewWindowSettings() [Internal]
13079
// - FindWindowSettings() [Internal]
13080
// - FindOrCreateWindowSettings() [Internal]
13081
// - FindSettingsHandler() [Internal]
13082
// - ClearIniSettings() [Internal]
13083
// - LoadIniSettingsFromDisk()
13084
// - LoadIniSettingsFromMemory()
13085
// - SaveIniSettingsToDisk()
13086
// - SaveIniSettingsToMemory()
13087
// - WindowSettingsHandler_***() [Internal]
13088
//-----------------------------------------------------------------------------
13089
13090
// Called by NewFrame()
13091
void ImGui::UpdateSettings()
13092
90.2k
{
13093
    // Load settings on first frame (if not explicitly loaded manually before)
13094
90.2k
    ImGuiContext& g = *GImGui;
13095
90.2k
    if (!g.SettingsLoaded)
13096
1
    {
13097
1
        IM_ASSERT(g.SettingsWindows.empty());
13098
1
        if (g.IO.IniFilename)
13099
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13100
1
        g.SettingsLoaded = true;
13101
1
    }
13102
13103
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13104
90.2k
    if (g.SettingsDirtyTimer > 0.0f)
13105
1.20k
    {
13106
1.20k
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13107
1.20k
        if (g.SettingsDirtyTimer <= 0.0f)
13108
4
        {
13109
4
            if (g.IO.IniFilename != NULL)
13110
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13111
4
            else
13112
4
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13113
4
            g.SettingsDirtyTimer = 0.0f;
13114
4
        }
13115
1.20k
    }
13116
90.2k
}
13117
13118
void ImGui::MarkIniSettingsDirty()
13119
0
{
13120
0
    ImGuiContext& g = *GImGui;
13121
0
    if (g.SettingsDirtyTimer <= 0.0f)
13122
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13123
0
}
13124
13125
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13126
131
{
13127
131
    ImGuiContext& g = *GImGui;
13128
131
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13129
32
        if (g.SettingsDirtyTimer <= 0.0f)
13130
4
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13131
131
}
13132
13133
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
13134
0
{
13135
0
    ImGuiContext& g = *GImGui;
13136
13137
0
#if !IMGUI_DEBUG_INI_SETTINGS
13138
    // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
13139
    // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
13140
0
    if (const char* p = strstr(name, "###"))
13141
0
        name = p;
13142
0
#endif
13143
0
    const size_t name_len = strlen(name);
13144
13145
    // Allocate chunk
13146
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
13147
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
13148
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
13149
0
    settings->ID = ImHashStr(name, name_len);
13150
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
13151
13152
0
    return settings;
13153
0
}
13154
13155
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
13156
2
{
13157
2
    ImGuiContext& g = *GImGui;
13158
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13159
0
        if (settings->ID == id)
13160
0
            return settings;
13161
2
    return NULL;
13162
2
}
13163
13164
ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
13165
0
{
13166
0
    if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
13167
0
        return settings;
13168
0
    return CreateNewWindowSettings(name);
13169
0
}
13170
13171
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13172
2
{
13173
2
    ImGuiContext& g = *GImGui;
13174
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13175
2
    g.SettingsHandlers.push_back(*handler);
13176
2
}
13177
13178
void ImGui::RemoveSettingsHandler(const char* type_name)
13179
0
{
13180
0
    ImGuiContext& g = *GImGui;
13181
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13182
0
        g.SettingsHandlers.erase(handler);
13183
0
}
13184
13185
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13186
2
{
13187
2
    ImGuiContext& g = *GImGui;
13188
2
    const ImGuiID type_hash = ImHashStr(type_name);
13189
3
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13190
1
        if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
13191
0
            return &g.SettingsHandlers[handler_n];
13192
2
    return NULL;
13193
2
}
13194
13195
void ImGui::ClearIniSettings()
13196
0
{
13197
0
    ImGuiContext& g = *GImGui;
13198
0
    g.SettingsIniData.clear();
13199
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13200
0
        if (g.SettingsHandlers[handler_n].ClearAllFn)
13201
0
            g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
13202
0
}
13203
13204
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13205
0
{
13206
0
    size_t file_data_size = 0;
13207
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13208
0
    if (!file_data)
13209
0
        return;
13210
0
    if (file_data_size > 0)
13211
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13212
0
    IM_FREE(file_data);
13213
0
}
13214
13215
// Zero-tolerance, no error reporting, cheap .ini parsing
13216
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13217
0
{
13218
0
    ImGuiContext& g = *GImGui;
13219
0
    IM_ASSERT(g.Initialized);
13220
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13221
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13222
13223
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13224
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13225
0
    if (ini_size == 0)
13226
0
        ini_size = strlen(ini_data);
13227
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13228
0
    char* const buf = g.SettingsIniData.Buf.Data;
13229
0
    char* const buf_end = buf + ini_size;
13230
0
    memcpy(buf, ini_data, ini_size);
13231
0
    buf_end[0] = 0;
13232
13233
    // Call pre-read handlers
13234
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13235
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13236
0
        if (g.SettingsHandlers[handler_n].ReadInitFn)
13237
0
            g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
13238
13239
0
    void* entry_data = NULL;
13240
0
    ImGuiSettingsHandler* entry_handler = NULL;
13241
13242
0
    char* line_end = NULL;
13243
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13244
0
    {
13245
        // Skip new lines markers, then find end of the line
13246
0
        while (*line == '\n' || *line == '\r')
13247
0
            line++;
13248
0
        line_end = line;
13249
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13250
0
            line_end++;
13251
0
        line_end[0] = 0;
13252
0
        if (line[0] == ';')
13253
0
            continue;
13254
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13255
0
        {
13256
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13257
0
            line_end[-1] = 0;
13258
0
            const char* name_end = line_end - 1;
13259
0
            const char* type_start = line + 1;
13260
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13261
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13262
0
            if (!type_end || !name_start)
13263
0
                continue;
13264
0
            *type_end = 0; // Overwrite first ']'
13265
0
            name_start++;  // Skip second '['
13266
0
            entry_handler = FindSettingsHandler(type_start);
13267
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13268
0
        }
13269
0
        else if (entry_handler != NULL && entry_data != NULL)
13270
0
        {
13271
            // Let type handler parse the line
13272
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13273
0
        }
13274
0
    }
13275
0
    g.SettingsLoaded = true;
13276
13277
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13278
0
    memcpy(buf, ini_data, ini_size);
13279
13280
    // Call post-read handlers
13281
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13282
0
        if (g.SettingsHandlers[handler_n].ApplyAllFn)
13283
0
            g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
13284
0
}
13285
13286
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13287
0
{
13288
0
    ImGuiContext& g = *GImGui;
13289
0
    g.SettingsDirtyTimer = 0.0f;
13290
0
    if (!ini_filename)
13291
0
        return;
13292
13293
0
    size_t ini_data_size = 0;
13294
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13295
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13296
0
    if (!f)
13297
0
        return;
13298
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13299
0
    ImFileClose(f);
13300
0
}
13301
13302
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13303
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13304
0
{
13305
0
    ImGuiContext& g = *GImGui;
13306
0
    g.SettingsDirtyTimer = 0.0f;
13307
0
    g.SettingsIniData.Buf.resize(0);
13308
0
    g.SettingsIniData.Buf.push_back(0);
13309
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13310
0
    {
13311
0
        ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
13312
0
        handler->WriteAllFn(&g, handler, &g.SettingsIniData);
13313
0
    }
13314
0
    if (out_size)
13315
0
        *out_size = (size_t)g.SettingsIniData.size();
13316
0
    return g.SettingsIniData.c_str();
13317
0
}
13318
13319
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13320
0
{
13321
0
    ImGuiContext& g = *ctx;
13322
0
    for (int i = 0; i != g.Windows.Size; i++)
13323
0
        g.Windows[i]->SettingsOffset = -1;
13324
0
    g.SettingsWindows.clear();
13325
0
}
13326
13327
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
13328
0
{
13329
0
    ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);
13330
0
    ImGuiID id = settings->ID;
13331
0
    *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
13332
0
    settings->ID = id;
13333
0
    settings->WantApply = true;
13334
0
    return (void*)settings;
13335
0
}
13336
13337
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
13338
0
{
13339
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
13340
0
    int x, y;
13341
0
    int i;
13342
0
    ImU32 u1;
13343
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
13344
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
13345
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
13346
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
13347
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
13348
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
13349
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
13350
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
13351
0
}
13352
13353
// Apply to existing windows (if any)
13354
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13355
0
{
13356
0
    ImGuiContext& g = *ctx;
13357
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13358
0
        if (settings->WantApply)
13359
0
        {
13360
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
13361
0
                ApplyWindowSettings(window, settings);
13362
0
            settings->WantApply = false;
13363
0
        }
13364
0
}
13365
13366
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
13367
0
{
13368
    // Gather data from windows that were active during this session
13369
    // (if a window wasn't opened in this session we preserve its settings)
13370
0
    ImGuiContext& g = *ctx;
13371
0
    for (int i = 0; i != g.Windows.Size; i++)
13372
0
    {
13373
0
        ImGuiWindow* window = g.Windows[i];
13374
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
13375
0
            continue;
13376
13377
0
        ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
13378
0
        if (!settings)
13379
0
        {
13380
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
13381
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
13382
0
        }
13383
0
        IM_ASSERT(settings->ID == window->ID);
13384
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
13385
0
        settings->Size = ImVec2ih(window->SizeFull);
13386
0
        settings->ViewportId = window->ViewportId;
13387
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
13388
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
13389
0
        settings->DockId = window->DockId;
13390
0
        settings->ClassId = window->WindowClass.ClassId;
13391
0
        settings->DockOrder = window->DockOrder;
13392
0
        settings->Collapsed = window->Collapsed;
13393
0
    }
13394
13395
    // Write to text buffer
13396
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
13397
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13398
0
    {
13399
0
        const char* settings_name = settings->GetName();
13400
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
13401
0
        if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13402
0
        {
13403
0
            buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
13404
0
            buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
13405
0
        }
13406
0
        if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13407
0
            buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
13408
0
        if (settings->Size.x != 0 || settings->Size.y != 0)
13409
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
13410
0
        buf->appendf("Collapsed=%d\n", settings->Collapsed);
13411
0
        if (settings->DockId != 0)
13412
0
        {
13413
            //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
13414
0
            if (settings->DockOrder == -1)
13415
0
                buf->appendf("DockId=0x%08X\n", settings->DockId);
13416
0
            else
13417
0
                buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
13418
0
            if (settings->ClassId != 0)
13419
0
                buf->appendf("ClassId=0x%08X\n", settings->ClassId);
13420
0
        }
13421
0
        buf->append("\n");
13422
0
    }
13423
0
}
13424
13425
13426
//-----------------------------------------------------------------------------
13427
// [SECTION] LOCALIZATION
13428
//-----------------------------------------------------------------------------
13429
13430
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
13431
1
{
13432
1
    ImGuiContext& g = *GImGui;
13433
9
    for (int n = 0; n < count; n++)
13434
8
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
13435
1
}
13436
13437
13438
//-----------------------------------------------------------------------------
13439
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
13440
//-----------------------------------------------------------------------------
13441
// - GetMainViewport()
13442
// - FindViewportByID()
13443
// - FindViewportByPlatformHandle()
13444
// - SetCurrentViewport() [Internal]
13445
// - SetWindowViewport() [Internal]
13446
// - GetWindowAlwaysWantOwnViewport() [Internal]
13447
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
13448
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
13449
// - TranslateWindowsInViewport() [Internal]
13450
// - ScaleWindowsInViewport() [Internal]
13451
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
13452
// - UpdateViewportsNewFrame() [Internal]
13453
// - UpdateViewportsEndFrame() [Internal]
13454
// - AddUpdateViewport() [Internal]
13455
// - WindowSelectViewport() [Internal]
13456
// - WindowSyncOwnedViewport() [Internal]
13457
// - UpdatePlatformWindows()
13458
// - RenderPlatformWindowsDefault()
13459
// - FindPlatformMonitorForPos() [Internal]
13460
// - FindPlatformMonitorForRect() [Internal]
13461
// - UpdateViewportPlatformMonitor() [Internal]
13462
// - DestroyPlatformWindow() [Internal]
13463
// - DestroyPlatformWindows()
13464
//-----------------------------------------------------------------------------
13465
13466
ImGuiViewport* ImGui::GetMainViewport()
13467
180k
{
13468
180k
    ImGuiContext& g = *GImGui;
13469
180k
    return g.Viewports[0];
13470
180k
}
13471
13472
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
13473
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
13474
90.2k
{
13475
90.2k
    ImGuiContext& g = *GImGui;
13476
90.2k
    for (int n = 0; n < g.Viewports.Size; n++)
13477
90.2k
        if (g.Viewports[n]->ID == id)
13478
90.2k
            return g.Viewports[n];
13479
0
    return NULL;
13480
90.2k
}
13481
13482
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
13483
0
{
13484
0
    ImGuiContext& g = *GImGui;
13485
0
    for (int i = 0; i != g.Viewports.Size; i++)
13486
0
        if (g.Viewports[i]->PlatformHandle == platform_handle)
13487
0
            return g.Viewports[i];
13488
0
    return NULL;
13489
0
}
13490
13491
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
13492
361k
{
13493
361k
    ImGuiContext& g = *GImGui;
13494
361k
    (void)current_window;
13495
13496
361k
    if (viewport)
13497
271k
        viewport->LastFrameActive = g.FrameCount;
13498
361k
    if (g.CurrentViewport == viewport)
13499
181k
        return;
13500
180k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
13501
180k
    g.CurrentViewport = viewport;
13502
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
13503
13504
    // Notify platform layer of viewport changes
13505
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
13506
180k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
13507
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
13508
180k
}
13509
13510
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13511
180k
{
13512
    // Abandon viewport
13513
180k
    if (window->ViewportOwned && window->Viewport->Window == window)
13514
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
13515
13516
180k
    window->Viewport = viewport;
13517
180k
    window->ViewportId = viewport->ID;
13518
180k
    window->ViewportOwned = (viewport->Window == window);
13519
180k
}
13520
13521
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
13522
0
{
13523
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
13524
0
    ImGuiContext& g = *GImGui;
13525
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
13526
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
13527
0
            if (!window->DockIsActive)
13528
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
13529
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
13530
0
                        return true;
13531
0
    return false;
13532
0
}
13533
13534
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13535
0
{
13536
0
    ImGuiContext& g = *GImGui;
13537
0
    if (window->Viewport == viewport)
13538
0
        return false;
13539
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
13540
0
        return false;
13541
0
    if ((viewport->Flags & ImGuiViewportFlags_Minimized) != 0)
13542
0
        return false;
13543
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
13544
0
        return false;
13545
0
    if (GetWindowAlwaysWantOwnViewport(window))
13546
0
        return false;
13547
13548
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
13549
0
    for (int n = 0; n < g.Windows.Size; n++)
13550
0
    {
13551
0
        ImGuiWindow* window_behind = g.Windows[n];
13552
0
        if (window_behind == window)
13553
0
            break;
13554
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
13555
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
13556
0
                return false;
13557
0
    }
13558
13559
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
13560
0
    ImGuiViewportP* old_viewport = window->Viewport;
13561
0
    if (window->ViewportOwned)
13562
0
        for (int n = 0; n < g.Windows.Size; n++)
13563
0
            if (g.Windows[n]->Viewport == old_viewport)
13564
0
                SetWindowViewport(g.Windows[n], viewport);
13565
0
    SetWindowViewport(window, viewport);
13566
0
    BringWindowToDisplayFront(window);
13567
13568
0
    return true;
13569
0
}
13570
13571
// FIXME: handle 0 to N host viewports
13572
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
13573
0
{
13574
0
    ImGuiContext& g = *GImGui;
13575
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
13576
0
}
13577
13578
// Translate Dear ImGui windows when a Host Viewport has been moved
13579
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13580
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
13581
0
{
13582
0
    ImGuiContext& g = *GImGui;
13583
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
13584
13585
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
13586
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
13587
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
13588
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
13589
    // and so the window will appear to teleport when releasing the mouse.
13590
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
13591
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
13592
0
    ImVec2 delta_pos = new_pos - old_pos;
13593
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
13594
0
        if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
13595
0
            TranslateWindow(g.Windows[window_n], delta_pos);
13596
0
}
13597
13598
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
13599
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
13600
0
{
13601
0
    ImGuiContext& g = *GImGui;
13602
0
    if (viewport->Window)
13603
0
    {
13604
0
        ScaleWindow(viewport->Window, scale);
13605
0
    }
13606
0
    else
13607
0
    {
13608
0
        for (int i = 0; i != g.Windows.Size; i++)
13609
0
            if (g.Windows[i]->Viewport == viewport)
13610
0
                ScaleWindow(g.Windows[i], scale);
13611
0
    }
13612
0
}
13613
13614
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
13615
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13616
// B) It requires Platform_GetWindowFocus to be implemented by backend.
13617
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
13618
0
{
13619
0
    ImGuiContext& g = *GImGui;
13620
0
    ImGuiViewportP* best_candidate = NULL;
13621
0
    for (int n = 0; n < g.Viewports.Size; n++)
13622
0
    {
13623
0
        ImGuiViewportP* viewport = g.Viewports[n];
13624
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
13625
0
            if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount)
13626
0
                best_candidate = viewport;
13627
0
    }
13628
0
    return best_candidate;
13629
0
}
13630
13631
// Update viewports and monitor infos
13632
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
13633
static void ImGui::UpdateViewportsNewFrame()
13634
90.2k
{
13635
90.2k
    ImGuiContext& g = *GImGui;
13636
90.2k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
13637
13638
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
13639
90.2k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
13640
90.2k
    if (viewports_enabled)
13641
0
    {
13642
0
        for (int n = 0; n < g.Viewports.Size; n++)
13643
0
        {
13644
0
            ImGuiViewportP* viewport = g.Viewports[n];
13645
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
13646
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
13647
0
            {
13648
0
                bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
13649
0
                if (minimized)
13650
0
                    viewport->Flags |= ImGuiViewportFlags_Minimized;
13651
0
                else
13652
0
                    viewport->Flags &= ~ImGuiViewportFlags_Minimized;
13653
0
            }
13654
0
        }
13655
0
    }
13656
13657
    // Create/update main viewport with current platform position.
13658
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
13659
90.2k
    ImGuiViewportP* main_viewport = g.Viewports[0];
13660
90.2k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
13661
90.2k
    IM_ASSERT(main_viewport->Window == NULL);
13662
90.2k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
13663
90.2k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
13664
90.2k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_Minimized))
13665
0
    {
13666
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
13667
0
        main_viewport_size = main_viewport->Size;
13668
0
    }
13669
90.2k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
13670
13671
90.2k
    g.CurrentDpiScale = 0.0f;
13672
90.2k
    g.CurrentViewport = NULL;
13673
90.2k
    g.MouseViewport = NULL;
13674
180k
    for (int n = 0; n < g.Viewports.Size; n++)
13675
90.2k
    {
13676
90.2k
        ImGuiViewportP* viewport = g.Viewports[n];
13677
90.2k
        viewport->Idx = n;
13678
13679
        // Erase unused viewports
13680
90.2k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
13681
0
        {
13682
0
            DestroyViewport(viewport);
13683
0
            n--;
13684
0
            continue;
13685
0
        }
13686
13687
90.2k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
13688
90.2k
        if (viewports_enabled)
13689
0
        {
13690
            // Update Position and Size (from Platform Window to ImGui) if requested.
13691
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
13692
0
            if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available)
13693
0
            {
13694
                // Viewport->WorkPos and WorkSize will be updated below
13695
0
                if (viewport->PlatformRequestMove)
13696
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
13697
0
                if (viewport->PlatformRequestResize)
13698
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
13699
0
            }
13700
0
        }
13701
13702
        // Update/copy monitor info
13703
90.2k
        UpdateViewportPlatformMonitor(viewport);
13704
13705
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
13706
90.2k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
13707
90.2k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
13708
90.2k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
13709
90.2k
        viewport->UpdateWorkRect();
13710
13711
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
13712
90.2k
        viewport->Alpha = 1.0f;
13713
13714
        // Translate Dear ImGui windows when a Host Viewport has been moved
13715
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13716
90.2k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
13717
90.2k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
13718
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
13719
13720
        // Update DPI scale
13721
90.2k
        float new_dpi_scale;
13722
90.2k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
13723
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
13724
90.2k
        else if (viewport->PlatformMonitor != -1)
13725
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
13726
90.2k
        else
13727
90.2k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
13728
90.2k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
13729
0
        {
13730
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
13731
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
13732
0
                ScaleWindowsInViewport(viewport, scale_factor);
13733
            //if (viewport == GetMainViewport())
13734
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
13735
13736
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
13737
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
13738
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
13739
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
13740
            //    g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
13741
0
        }
13742
90.2k
        viewport->DpiScale = new_dpi_scale;
13743
90.2k
    }
13744
13745
    // Update fallback monitor
13746
90.2k
    if (g.PlatformIO.Monitors.Size == 0)
13747
90.2k
    {
13748
90.2k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
13749
90.2k
        monitor->MainPos = main_viewport->Pos;
13750
90.2k
        monitor->MainSize = main_viewport->Size;
13751
90.2k
        monitor->WorkPos = main_viewport->WorkPos;
13752
90.2k
        monitor->WorkSize = main_viewport->WorkSize;
13753
90.2k
        monitor->DpiScale = main_viewport->DpiScale;
13754
90.2k
    }
13755
13756
90.2k
    if (!viewports_enabled)
13757
90.2k
    {
13758
90.2k
        g.MouseViewport = main_viewport;
13759
90.2k
        return;
13760
90.2k
    }
13761
13762
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
13763
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
13764
0
    ImGuiViewportP* viewport_hovered = NULL;
13765
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
13766
0
    {
13767
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
13768
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
13769
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
13770
0
    }
13771
0
    else
13772
0
    {
13773
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
13774
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13775
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
13776
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
13777
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
13778
0
    }
13779
0
    if (viewport_hovered != NULL)
13780
0
        g.MouseLastHoveredViewport = viewport_hovered;
13781
0
    else if (g.MouseLastHoveredViewport == NULL)
13782
0
        g.MouseLastHoveredViewport = g.Viewports[0];
13783
13784
    // Update mouse reference viewport
13785
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
13786
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
13787
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
13788
0
        g.MouseViewport = g.MovingWindow->Viewport;
13789
0
    else
13790
0
        g.MouseViewport = g.MouseLastHoveredViewport;
13791
13792
    // When dragging something, always refer to the last hovered viewport.
13793
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
13794
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
13795
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
13796
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
13797
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
13798
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
13799
0
        viewport_hovered = g.MouseLastHoveredViewport;
13800
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
13801
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
13802
0
            g.MouseViewport = viewport_hovered;
13803
13804
0
    IM_ASSERT(g.MouseViewport != NULL);
13805
0
}
13806
13807
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
13808
static void ImGui::UpdateViewportsEndFrame()
13809
90.2k
{
13810
90.2k
    ImGuiContext& g = *GImGui;
13811
90.2k
    g.PlatformIO.Viewports.resize(0);
13812
180k
    for (int i = 0; i < g.Viewports.Size; i++)
13813
90.2k
    {
13814
90.2k
        ImGuiViewportP* viewport = g.Viewports[i];
13815
90.2k
        viewport->LastPos = viewport->Pos;
13816
90.2k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
13817
0
            if (i > 0) // Always include main viewport in the list
13818
0
                continue;
13819
90.2k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
13820
0
            continue;
13821
90.2k
        if (i > 0)
13822
90.2k
            IM_ASSERT(viewport->Window != NULL);
13823
90.2k
        g.PlatformIO.Viewports.push_back(viewport);
13824
90.2k
    }
13825
90.2k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
13826
90.2k
}
13827
13828
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
13829
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
13830
90.2k
{
13831
90.2k
    ImGuiContext& g = *GImGui;
13832
90.2k
    IM_ASSERT(id != 0);
13833
13834
90.2k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
13835
90.2k
    if (window != NULL)
13836
0
    {
13837
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
13838
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
13839
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
13840
0
            flags |= ImGuiViewportFlags_NoInputs;
13841
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
13842
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
13843
0
    }
13844
13845
90.2k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
13846
90.2k
    if (viewport)
13847
90.2k
    {
13848
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
13849
90.2k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
13850
90.2k
            viewport->Pos = pos;
13851
90.2k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
13852
90.2k
            viewport->Size = size;
13853
90.2k
        viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags
13854
90.2k
    }
13855
0
    else
13856
0
    {
13857
        // New viewport
13858
0
        viewport = IM_NEW(ImGuiViewportP)();
13859
0
        viewport->ID = id;
13860
0
        viewport->Idx = g.Viewports.Size;
13861
0
        viewport->Pos = viewport->LastPos = pos;
13862
0
        viewport->Size = size;
13863
0
        viewport->Flags = flags;
13864
0
        UpdateViewportPlatformMonitor(viewport);
13865
0
        g.Viewports.push_back(viewport);
13866
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
13867
13868
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
13869
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
13870
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
13871
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
13872
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
13873
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
13874
13875
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
13876
        // This is so we can select an appropriate font size on the first frame of our window lifetime
13877
0
        if (viewport->PlatformMonitor != -1)
13878
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
13879
0
    }
13880
13881
90.2k
    viewport->Window = window;
13882
90.2k
    viewport->LastFrameActive = g.FrameCount;
13883
90.2k
    viewport->UpdateWorkRect();
13884
90.2k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
13885
13886
90.2k
    if (window != NULL)
13887
0
        window->ViewportOwned = true;
13888
13889
90.2k
    return viewport;
13890
90.2k
}
13891
13892
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
13893
0
{
13894
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
13895
0
    ImGuiContext& g = *GImGui;
13896
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
13897
0
    {
13898
0
        ImGuiWindow* window = g.Windows[window_n];
13899
0
        if (window->Viewport != viewport)
13900
0
            continue;
13901
0
        window->Viewport = NULL;
13902
0
        window->ViewportOwned = false;
13903
0
    }
13904
0
    if (viewport == g.MouseLastHoveredViewport)
13905
0
        g.MouseLastHoveredViewport = NULL;
13906
13907
    // Destroy
13908
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
13909
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
13910
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
13911
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
13912
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
13913
0
    IM_DELETE(viewport);
13914
0
}
13915
13916
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
13917
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
13918
180k
{
13919
180k
    ImGuiContext& g = *GImGui;
13920
180k
    ImGuiWindowFlags flags = window->Flags;
13921
180k
    window->ViewportAllowPlatformMonitorExtend = -1;
13922
13923
    // Restore main viewport if multi-viewport is not supported by the backend
13924
180k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
13925
180k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
13926
180k
    {
13927
180k
        SetWindowViewport(window, main_viewport);
13928
180k
        return;
13929
180k
    }
13930
0
    window->ViewportOwned = false;
13931
13932
    // Appearing popups reset their viewport so they can inherit again
13933
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
13934
0
    {
13935
0
        window->Viewport = NULL;
13936
0
        window->ViewportId = 0;
13937
0
    }
13938
13939
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
13940
0
    {
13941
        // By default inherit from parent window
13942
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
13943
0
            window->Viewport = window->ParentWindow->Viewport;
13944
13945
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
13946
0
        if (window->Viewport == NULL && window->ViewportId != 0)
13947
0
        {
13948
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
13949
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
13950
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
13951
0
        }
13952
0
    }
13953
13954
0
    bool lock_viewport = false;
13955
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
13956
0
    {
13957
        // Code explicitly request a viewport
13958
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
13959
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
13960
0
        lock_viewport = true;
13961
0
    }
13962
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
13963
0
    {
13964
        // Always inherit viewport from parent window
13965
0
        if (window->DockNode && window->DockNode->HostWindow)
13966
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
13967
0
        window->Viewport = window->ParentWindow->Viewport;
13968
0
    }
13969
0
    else if (window->DockNode && window->DockNode->HostWindow)
13970
0
    {
13971
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
13972
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
13973
0
    }
13974
0
    else if (flags & ImGuiWindowFlags_Tooltip)
13975
0
    {
13976
0
        window->Viewport = g.MouseViewport;
13977
0
    }
13978
0
    else if (GetWindowAlwaysWantOwnViewport(window))
13979
0
    {
13980
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
13981
0
    }
13982
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
13983
0
    {
13984
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
13985
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
13986
0
    }
13987
0
    else
13988
0
    {
13989
        // Merge into host viewport?
13990
        // We cannot test window->ViewportOwned as it set lower in the function.
13991
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
13992
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
13993
0
        if (try_to_merge_into_host_viewport)
13994
0
            UpdateTryMergeWindowIntoHostViewports(window);
13995
0
    }
13996
13997
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
13998
0
    if (window->Viewport == NULL)
13999
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14000
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14001
14002
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14003
0
    if (!lock_viewport)
14004
0
    {
14005
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14006
0
        {
14007
            // We need to take account of the possibility that mouse may become invalid.
14008
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14009
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14010
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14011
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14012
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14013
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14014
0
            else
14015
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14016
0
        }
14017
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14018
0
        {
14019
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14020
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14021
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14022
0
            {
14023
                // Steal/transfer ownership
14024
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14025
0
                window->Viewport->Window = window;
14026
0
                window->Viewport->ID = window->ID;
14027
0
                window->Viewport->LastNameHash = 0;
14028
0
            }
14029
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14030
0
            {
14031
                // New viewport
14032
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14033
0
            }
14034
0
        }
14035
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14036
0
        {
14037
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14038
            // Child windows are kept contained within their parent.
14039
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14040
0
        }
14041
0
    }
14042
14043
    // Update flags
14044
0
    window->ViewportOwned = (window == window->Viewport->Window);
14045
0
    window->ViewportId = window->Viewport->ID;
14046
14047
    // If the OS window has a title bar, hide our imgui title bar
14048
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14049
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14050
0
}
14051
14052
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14053
0
{
14054
0
    ImGuiContext& g = *GImGui;
14055
14056
0
    bool viewport_rect_changed = false;
14057
14058
    // Synchronize window --> viewport in most situations
14059
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14060
0
    if (window->Viewport->PlatformRequestMove)
14061
0
    {
14062
0
        window->Pos = window->Viewport->Pos;
14063
0
        MarkIniSettingsDirty(window);
14064
0
    }
14065
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14066
0
    {
14067
0
        viewport_rect_changed = true;
14068
0
        window->Viewport->Pos = window->Pos;
14069
0
    }
14070
14071
0
    if (window->Viewport->PlatformRequestResize)
14072
0
    {
14073
0
        window->Size = window->SizeFull = window->Viewport->Size;
14074
0
        MarkIniSettingsDirty(window);
14075
0
    }
14076
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14077
0
    {
14078
0
        viewport_rect_changed = true;
14079
0
        window->Viewport->Size = window->Size;
14080
0
    }
14081
0
    window->Viewport->UpdateWorkRect();
14082
14083
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14084
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14085
0
    if (viewport_rect_changed)
14086
0
        UpdateViewportPlatformMonitor(window->Viewport);
14087
14088
    // Update common viewport flags
14089
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14090
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14091
0
    ImGuiWindowFlags window_flags = window->Flags;
14092
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14093
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14094
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14095
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14096
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14097
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14098
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14099
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14100
14101
    // Not correct to set modal as topmost because:
14102
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14103
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14104
    //if (flags & ImGuiWindowFlags_Modal)
14105
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14106
14107
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14108
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14109
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14110
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14111
0
    if (is_short_lived_floating_window && !is_modal)
14112
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14113
14114
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14115
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14116
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14117
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14118
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14119
14120
    // We can also tell the backend that clearing the platform window won't be necessary,
14121
    // as our window background is filling the viewport and we have disabled BgAlpha.
14122
    // FIXME: Work on support for per-viewport transparency (#2766)
14123
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14124
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14125
14126
0
    window->Viewport->Flags = viewport_flags;
14127
14128
    // Update parent viewport ID
14129
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14130
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14131
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14132
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14133
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14134
0
    else
14135
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14136
0
}
14137
14138
// Called by user at the end of the main loop, after EndFrame()
14139
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14140
void ImGui::UpdatePlatformWindows()
14141
0
{
14142
0
    ImGuiContext& g = *GImGui;
14143
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14144
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14145
0
    g.FrameCountPlatformEnded = g.FrameCount;
14146
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14147
0
        return;
14148
14149
    // Create/resize/destroy platform windows to match each active viewport.
14150
    // Skip the main viewport (index 0), which is always fully handled by the application!
14151
0
    for (int i = 1; i < g.Viewports.Size; i++)
14152
0
    {
14153
0
        ImGuiViewportP* viewport = g.Viewports[i];
14154
14155
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14156
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14157
0
        bool destroy_platform_window = false;
14158
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14159
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14160
0
        if (destroy_platform_window)
14161
0
        {
14162
0
            DestroyPlatformWindow(viewport);
14163
0
            continue;
14164
0
        }
14165
14166
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14167
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14168
0
            continue;
14169
14170
        // Create window
14171
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14172
0
        if (is_new_platform_window)
14173
0
        {
14174
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14175
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14176
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14177
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14178
0
            viewport->LastNameHash = 0;
14179
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14180
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14181
0
            viewport->PlatformWindowCreated = true;
14182
0
        }
14183
14184
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14185
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14186
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
14187
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
14188
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
14189
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
14190
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
14191
0
        viewport->LastPlatformPos = viewport->Pos;
14192
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
14193
14194
        // Update title bar (if it changed)
14195
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
14196
0
        {
14197
0
            const char* title_begin = window_for_title->Name;
14198
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
14199
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
14200
0
            if (viewport->LastNameHash != title_hash)
14201
0
            {
14202
0
                char title_end_backup_c = *title_end;
14203
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
14204
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
14205
0
                *title_end = title_end_backup_c;
14206
0
                viewport->LastNameHash = title_hash;
14207
0
            }
14208
0
        }
14209
14210
        // Update alpha (if it changed)
14211
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
14212
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
14213
0
        viewport->LastAlpha = viewport->Alpha;
14214
14215
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
14216
0
        if (g.PlatformIO.Platform_UpdateWindow)
14217
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
14218
14219
0
        if (is_new_platform_window)
14220
0
        {
14221
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
14222
0
            if (g.FrameCount < 3)
14223
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14224
14225
            // Show window
14226
0
            g.PlatformIO.Platform_ShowWindow(viewport);
14227
14228
            // Even without focus, we assume the window becomes front-most.
14229
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
14230
0
            if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
14231
0
                viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
14232
0
            }
14233
14234
        // Clear request flags
14235
0
        viewport->ClearRequestFlags();
14236
0
    }
14237
14238
    // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14239
    // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14240
    // FIXME-VIEWPORT: We should use this information to also set dear imgui-side focus, allowing us to handle os-level alt+tab.
14241
0
    if (g.PlatformIO.Platform_GetWindowFocus != NULL)
14242
0
    {
14243
0
        ImGuiViewportP* focused_viewport = NULL;
14244
0
        for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++)
14245
0
        {
14246
0
            ImGuiViewportP* viewport = g.Viewports[n];
14247
0
            if (viewport->PlatformWindowCreated)
14248
0
                if (g.PlatformIO.Platform_GetWindowFocus(viewport))
14249
0
                    focused_viewport = viewport;
14250
0
        }
14251
14252
        // Store a tag so we can infer z-order easily from all our windows
14253
        // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14254
        // will keep the front most stamp instead of losing it back to their parent viewport.
14255
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14256
0
        {
14257
0
            if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
14258
0
                focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
14259
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14260
0
        }
14261
0
    }
14262
0
}
14263
14264
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
14265
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
14266
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
14267
//
14268
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14269
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14270
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14271
//            MyRenderFunction(platform_io.Viewports[i], my_args);
14272
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14273
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14274
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
14275
//
14276
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
14277
0
{
14278
    // Skip the main viewport (index 0), which is always fully handled by the application!
14279
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14280
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14281
0
    {
14282
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14283
0
        if (viewport->Flags & ImGuiViewportFlags_Minimized)
14284
0
            continue;
14285
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
14286
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
14287
0
    }
14288
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14289
0
    {
14290
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14291
0
        if (viewport->Flags & ImGuiViewportFlags_Minimized)
14292
0
            continue;
14293
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
14294
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
14295
0
    }
14296
0
}
14297
14298
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
14299
0
{
14300
0
    ImGuiContext& g = *GImGui;
14301
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
14302
0
    {
14303
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14304
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
14305
0
            return monitor_n;
14306
0
    }
14307
0
    return -1;
14308
0
}
14309
14310
// Search for the monitor with the largest intersection area with the given rectangle
14311
// We generally try to avoid searching loops but the monitor count should be very small here
14312
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
14313
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
14314
90.2k
{
14315
90.2k
    ImGuiContext& g = *GImGui;
14316
14317
90.2k
    const int monitor_count = g.PlatformIO.Monitors.Size;
14318
90.2k
    if (monitor_count <= 1)
14319
90.2k
        return monitor_count - 1;
14320
14321
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
14322
    // This is necessary for tooltips which always resize down to zero at first.
14323
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
14324
0
    int best_monitor_n = -1;
14325
0
    float best_monitor_surface = 0.001f;
14326
14327
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
14328
0
    {
14329
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14330
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
14331
0
        if (monitor_rect.Contains(rect))
14332
0
            return monitor_n;
14333
0
        ImRect overlapping_rect = rect;
14334
0
        overlapping_rect.ClipWithFull(monitor_rect);
14335
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
14336
0
        if (overlapping_surface < best_monitor_surface)
14337
0
            continue;
14338
0
        best_monitor_surface = overlapping_surface;
14339
0
        best_monitor_n = monitor_n;
14340
0
    }
14341
0
    return best_monitor_n;
14342
0
}
14343
14344
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
14345
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
14346
90.2k
{
14347
90.2k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
14348
90.2k
}
14349
14350
// Return value is always != NULL, but don't hold on it across frames.
14351
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
14352
0
{
14353
0
    ImGuiContext& g = *GImGui;
14354
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
14355
0
    int monitor_idx = viewport->PlatformMonitor;
14356
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
14357
0
        return &g.PlatformIO.Monitors[monitor_idx];
14358
0
    return &g.FallbackMonitor;
14359
0
}
14360
14361
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
14362
0
{
14363
0
    ImGuiContext& g = *GImGui;
14364
0
    if (viewport->PlatformWindowCreated)
14365
0
    {
14366
0
        if (g.PlatformIO.Renderer_DestroyWindow)
14367
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
14368
0
        if (g.PlatformIO.Platform_DestroyWindow)
14369
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
14370
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
14371
14372
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
14373
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
14374
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
14375
0
            viewport->PlatformWindowCreated = false;
14376
0
    }
14377
0
    else
14378
0
    {
14379
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
14380
0
    }
14381
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
14382
0
    viewport->ClearRequestFlags();
14383
0
}
14384
14385
void ImGui::DestroyPlatformWindows()
14386
0
{
14387
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
14388
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
14389
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
14390
    // code to operator a consistent manner.
14391
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
14392
    // crashing if it doesn't have data stored.
14393
0
    ImGuiContext& g = *GImGui;
14394
0
    for (int i = 0; i < g.Viewports.Size; i++)
14395
0
        DestroyPlatformWindow(g.Viewports[i]);
14396
0
}
14397
14398
14399
//-----------------------------------------------------------------------------
14400
// [SECTION] DOCKING
14401
//-----------------------------------------------------------------------------
14402
// Docking: Internal Types
14403
// Docking: Forward Declarations
14404
// Docking: ImGuiDockContext
14405
// Docking: ImGuiDockContext Docking/Undocking functions
14406
// Docking: ImGuiDockNode
14407
// Docking: ImGuiDockNode Tree manipulation functions
14408
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
14409
// Docking: Builder Functions
14410
// Docking: Begin/End Support Functions (called from Begin/End)
14411
// Docking: Settings
14412
//-----------------------------------------------------------------------------
14413
14414
//-----------------------------------------------------------------------------
14415
// Typical Docking call flow: (root level is generally public API):
14416
//-----------------------------------------------------------------------------
14417
// - NewFrame()                               new dear imgui frame
14418
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
14419
//    | - DockContextProcessUndockWindow()    - process one window undocking request
14420
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
14421
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
14422
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
14423
//    | - DockContextProcessDock()            - process one docking request
14424
//    | - DockNodeUpdate()
14425
//    |   - DockNodeUpdateForRootNode()
14426
//    |     - DockNodeUpdateFlagsAndCollapse()
14427
//    |     - DockNodeFindInfo()
14428
//    |   - destroy unused node or tab bar
14429
//    |   - create dock node host window
14430
//    |      - Begin() etc.
14431
//    |   - DockNodeStartMouseMovingWindow()
14432
//    |   - DockNodeTreeUpdatePosSize()
14433
//    |   - DockNodeTreeUpdateSplitter()
14434
//    |   - draw node background
14435
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
14436
//    |     - DockNodeAddTabBar()
14437
//    |     - DockNodeUpdateWindowMenu()
14438
//    |     - DockNodeCalcTabBarLayout()
14439
//    |     - BeginTabBarEx()
14440
//    |     - TabItemEx() calls
14441
//    |     - EndTabBar()
14442
//    |   - BeginDockableDragDropTarget()
14443
//    |      - DockNodeUpdate()               - recurse into child nodes...
14444
//-----------------------------------------------------------------------------
14445
// - DockSpace()                              user submit a dockspace into a window
14446
//    | Begin(Child)                          - create a child window
14447
//    | DockNodeUpdate()                      - call main dock node update function
14448
//    | End(Child)
14449
//    | ItemSize()
14450
//-----------------------------------------------------------------------------
14451
// - Begin()
14452
//    | BeginDocked()
14453
//    | BeginDockableDragDropSource()
14454
//    | BeginDockableDragDropTarget()
14455
//    | - DockNodePreviewDockRender()
14456
//-----------------------------------------------------------------------------
14457
// - EndFrame()
14458
//    | DockContextEndFrame()
14459
//-----------------------------------------------------------------------------
14460
14461
//-----------------------------------------------------------------------------
14462
// Docking: Internal Types
14463
//-----------------------------------------------------------------------------
14464
// - ImGuiDockRequestType
14465
// - ImGuiDockRequest
14466
// - ImGuiDockPreviewData
14467
// - ImGuiDockNodeSettings
14468
// - ImGuiDockContext
14469
//-----------------------------------------------------------------------------
14470
14471
enum ImGuiDockRequestType
14472
{
14473
    ImGuiDockRequestType_None = 0,
14474
    ImGuiDockRequestType_Dock,
14475
    ImGuiDockRequestType_Undock,
14476
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
14477
};
14478
14479
struct ImGuiDockRequest
14480
{
14481
    ImGuiDockRequestType    Type;
14482
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
14483
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
14484
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
14485
    ImGuiDir                DockSplitDir;
14486
    float                   DockSplitRatio;
14487
    bool                    DockSplitOuter;
14488
    ImGuiWindow*            UndockTargetWindow;
14489
    ImGuiDockNode*          UndockTargetNode;
14490
14491
    ImGuiDockRequest()
14492
0
    {
14493
0
        Type = ImGuiDockRequestType_None;
14494
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
14495
0
        DockTargetNode = UndockTargetNode = NULL;
14496
0
        DockSplitDir = ImGuiDir_None;
14497
0
        DockSplitRatio = 0.5f;
14498
0
        DockSplitOuter = false;
14499
0
    }
14500
};
14501
14502
struct ImGuiDockPreviewData
14503
{
14504
    ImGuiDockNode   FutureNode;
14505
    bool            IsDropAllowed;
14506
    bool            IsCenterAvailable;
14507
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
14508
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
14509
    ImGuiDockNode*  SplitNode;
14510
    ImGuiDir        SplitDir;
14511
    float           SplitRatio;
14512
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
14513
14514
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
14515
};
14516
14517
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
14518
struct ImGuiDockNodeSettings
14519
{
14520
    ImGuiID             ID;
14521
    ImGuiID             ParentNodeId;
14522
    ImGuiID             ParentWindowId;
14523
    ImGuiID             SelectedTabId;
14524
    signed char         SplitAxis;
14525
    char                Depth;
14526
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
14527
    ImVec2ih            Pos;
14528
    ImVec2ih            Size;
14529
    ImVec2ih            SizeRef;
14530
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
14531
};
14532
14533
//-----------------------------------------------------------------------------
14534
// Docking: Forward Declarations
14535
//-----------------------------------------------------------------------------
14536
14537
namespace ImGui
14538
{
14539
    // ImGuiDockContext
14540
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
14541
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
14542
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
14543
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
14544
    static void             DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true);
14545
    static void             DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node);
14546
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
14547
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
14548
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
14549
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
14550
14551
    // ImGuiDockNode
14552
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
14553
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14554
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14555
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
14556
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
14557
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
14558
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
14559
    static void             DockNodeUpdate(ImGuiDockNode* node);
14560
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
14561
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
14562
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
14563
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
14564
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
14565
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
14566
    static ImGuiID          DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
14567
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
14568
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
14569
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
14570
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
14571
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
14572
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
14573
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
14574
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
14575
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
14576
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
14577
14578
    // ImGuiDockNode tree manipulations
14579
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
14580
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
14581
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
14582
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
14583
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
14584
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
14585
14586
    // Settings
14587
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
14588
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
14589
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
14590
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
14591
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
14592
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
14593
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
14594
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
14595
}
14596
14597
//-----------------------------------------------------------------------------
14598
// Docking: ImGuiDockContext
14599
//-----------------------------------------------------------------------------
14600
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
14601
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
14602
// At boot time only, we run a simple GC to remove nodes that have no references.
14603
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
14604
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
14605
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
14606
//-----------------------------------------------------------------------------
14607
// - DockContextInitialize()
14608
// - DockContextShutdown()
14609
// - DockContextClearNodes()
14610
// - DockContextRebuildNodes()
14611
// - DockContextNewFrameUpdateUndocking()
14612
// - DockContextNewFrameUpdateDocking()
14613
// - DockContextEndFrame()
14614
// - DockContextFindNodeByID()
14615
// - DockContextBindNodeToWindow()
14616
// - DockContextGenNodeID()
14617
// - DockContextAddNode()
14618
// - DockContextRemoveNode()
14619
// - ImGuiDockContextPruneNodeData
14620
// - DockContextPruneUnusedSettingsNodes()
14621
// - DockContextBuildNodesFromSettings()
14622
// - DockContextBuildAddWindowsToNodes()
14623
//-----------------------------------------------------------------------------
14624
14625
void ImGui::DockContextInitialize(ImGuiContext* ctx)
14626
1
{
14627
1
    ImGuiContext& g = *ctx;
14628
14629
    // Add .ini handle for persistent docking data
14630
1
    ImGuiSettingsHandler ini_handler;
14631
1
    ini_handler.TypeName = "Docking";
14632
1
    ini_handler.TypeHash = ImHashStr("Docking");
14633
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
14634
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
14635
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
14636
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
14637
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
14638
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
14639
1
    g.SettingsHandlers.push_back(ini_handler);
14640
1
}
14641
14642
void ImGui::DockContextShutdown(ImGuiContext* ctx)
14643
0
{
14644
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14645
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14646
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14647
0
            IM_DELETE(node);
14648
0
}
14649
14650
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
14651
0
{
14652
0
    IM_UNUSED(ctx);
14653
0
    IM_ASSERT(ctx == GImGui);
14654
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
14655
0
    DockBuilderRemoveNodeChildNodes(root_id);
14656
0
}
14657
14658
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
14659
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
14660
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
14661
0
{
14662
0
    ImGuiContext& g = *ctx;
14663
0
    ImGuiDockContext* dc = &ctx->DockContext;
14664
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
14665
0
    SaveIniSettingsToMemory();
14666
0
    ImGuiID root_id = 0; // Rebuild all
14667
0
    DockContextClearNodes(ctx, root_id, false);
14668
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
14669
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
14670
0
}
14671
14672
// Docking context update function, called by NewFrame()
14673
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
14674
90.2k
{
14675
90.2k
    ImGuiContext& g = *ctx;
14676
90.2k
    ImGuiDockContext* dc = &ctx->DockContext;
14677
90.2k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
14678
0
    {
14679
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
14680
0
            DockContextClearNodes(ctx, 0, true);
14681
0
        return;
14682
0
    }
14683
14684
    // Setting NoSplit at runtime merges all nodes
14685
90.2k
    if (g.IO.ConfigDockingNoSplit)
14686
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
14687
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14688
0
                if (node->IsRootNode() && node->IsSplitNode())
14689
0
                {
14690
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
14691
                    //dc->WantFullRebuild = true;
14692
0
                }
14693
14694
    // Process full rebuild
14695
#if 0
14696
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
14697
        dc->WantFullRebuild = true;
14698
#endif
14699
90.2k
    if (dc->WantFullRebuild)
14700
0
    {
14701
0
        DockContextRebuildNodes(ctx);
14702
0
        dc->WantFullRebuild = false;
14703
0
    }
14704
14705
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
14706
90.2k
    for (int n = 0; n < dc->Requests.Size; n++)
14707
0
    {
14708
0
        ImGuiDockRequest* req = &dc->Requests[n];
14709
0
        if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
14710
0
            DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
14711
0
        else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
14712
0
            DockContextProcessUndockNode(ctx, req->UndockTargetNode);
14713
0
    }
14714
90.2k
}
14715
14716
// Docking context update function, called by NewFrame()
14717
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
14718
90.2k
{
14719
90.2k
    ImGuiContext& g = *ctx;
14720
90.2k
    ImGuiDockContext* dc  = &ctx->DockContext;
14721
90.2k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
14722
0
        return;
14723
14724
    // [DEBUG] Store hovered dock node.
14725
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
14726
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
14727
90.2k
    g.DebugHoveredDockNode = NULL;
14728
90.2k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
14729
334
    {
14730
334
        if (hovered_window->DockNodeAsHost)
14731
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
14732
334
        else if (hovered_window->RootWindow->DockNode)
14733
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
14734
334
    }
14735
14736
    // Process Docking requests
14737
90.2k
    for (int n = 0; n < dc->Requests.Size; n++)
14738
0
        if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
14739
0
            DockContextProcessDock(ctx, &dc->Requests[n]);
14740
90.2k
    dc->Requests.resize(0);
14741
14742
    // Create windows for each automatic docking nodes
14743
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
14744
90.2k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14745
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14746
0
            if (node->IsFloatingNode())
14747
0
                DockNodeUpdate(node);
14748
90.2k
}
14749
14750
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
14751
90.2k
{
14752
    // Draw backgrounds of node missing their window
14753
90.2k
    ImGuiContext& g = *ctx;
14754
90.2k
    ImGuiDockContext* dc = &g.DockContext;
14755
90.2k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14756
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14757
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
14758
0
            {
14759
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
14760
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), DOCKING_SPLITTER_SIZE);
14761
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
14762
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
14763
0
            }
14764
90.2k
}
14765
14766
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
14767
0
{
14768
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
14769
0
}
14770
14771
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
14772
0
{
14773
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
14774
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
14775
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
14776
0
    ImGuiID id = 0x0001;
14777
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
14778
0
        id++;
14779
0
    return id;
14780
0
}
14781
14782
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
14783
0
{
14784
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
14785
0
    ImGuiContext& g = *ctx;
14786
0
    if (id == 0)
14787
0
        id = DockContextGenNodeID(ctx);
14788
0
    else
14789
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
14790
14791
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
14792
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
14793
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
14794
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
14795
0
    return node;
14796
0
}
14797
14798
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
14799
0
{
14800
0
    ImGuiContext& g = *ctx;
14801
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14802
14803
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
14804
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
14805
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
14806
0
    IM_ASSERT(node->Windows.Size == 0);
14807
14808
0
    if (node->HostWindow)
14809
0
        node->HostWindow->DockNodeAsHost = NULL;
14810
14811
0
    ImGuiDockNode* parent_node = node->ParentNode;
14812
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
14813
0
    if (merge)
14814
0
    {
14815
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
14816
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
14817
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
14818
0
    }
14819
0
    else
14820
0
    {
14821
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
14822
0
            if (parent_node->ChildNodes[n] == node)
14823
0
                node->ParentNode->ChildNodes[n] = NULL;
14824
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
14825
0
        IM_DELETE(node);
14826
0
    }
14827
0
}
14828
14829
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
14830
0
{
14831
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
14832
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
14833
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
14834
0
}
14835
14836
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
14837
struct ImGuiDockContextPruneNodeData
14838
{
14839
    int         CountWindows, CountChildWindows, CountChildNodes;
14840
    ImGuiID     RootId;
14841
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
14842
};
14843
14844
// Garbage collect unused nodes (run once at init time)
14845
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
14846
0
{
14847
0
    ImGuiContext& g = *ctx;
14848
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14849
0
    IM_ASSERT(g.Windows.Size == 0);
14850
14851
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
14852
0
    pool.Reserve(dc->NodesSettings.Size);
14853
14854
    // Count child nodes and compute RootID
14855
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14856
0
    {
14857
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14858
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
14859
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
14860
0
        if (settings->ParentNodeId)
14861
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
14862
0
    }
14863
14864
    // Count reference to dock ids from dockspaces
14865
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
14866
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14867
0
    {
14868
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14869
0
        if (settings->ParentWindowId != 0)
14870
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->ParentWindowId))
14871
0
                if (window_settings->DockId)
14872
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
14873
0
                        data->CountChildNodes++;
14874
0
    }
14875
14876
    // Count reference to dock ids from window settings
14877
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
14878
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14879
0
        if (ImGuiID dock_id = settings->DockId)
14880
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
14881
0
            {
14882
0
                data->CountWindows++;
14883
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
14884
0
                    data_root->CountChildWindows++;
14885
0
            }
14886
14887
    // Prune
14888
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14889
0
    {
14890
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14891
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
14892
0
        if (data->CountWindows > 1)
14893
0
            continue;
14894
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
14895
14896
0
        bool remove = false;
14897
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
14898
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
14899
0
        remove |= (data_root->CountChildWindows == 0);
14900
0
        if (remove)
14901
0
        {
14902
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
14903
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
14904
0
            settings->ID = 0;
14905
0
        }
14906
0
    }
14907
0
}
14908
14909
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
14910
0
{
14911
    // Build nodes
14912
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
14913
0
    {
14914
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
14915
0
        if (settings->ID == 0)
14916
0
            continue;
14917
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
14918
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
14919
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
14920
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
14921
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
14922
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
14923
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
14924
0
            node->ParentNode->ChildNodes[0] = node;
14925
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
14926
0
            node->ParentNode->ChildNodes[1] = node;
14927
0
        node->SelectedTabId = settings->SelectedTabId;
14928
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
14929
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
14930
14931
        // Bind host window immediately if it already exist (in case of a rebuild)
14932
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
14933
0
        char host_window_title[20];
14934
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
14935
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
14936
0
    }
14937
0
}
14938
14939
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
14940
0
{
14941
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
14942
0
    ImGuiContext& g = *ctx;
14943
0
    for (int n = 0; n < g.Windows.Size; n++)
14944
0
    {
14945
0
        ImGuiWindow* window = g.Windows[n];
14946
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
14947
0
            continue;
14948
0
        if (window->DockNode != NULL)
14949
0
            continue;
14950
14951
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
14952
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
14953
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
14954
0
            DockNodeAddWindow(node, window, true);
14955
0
    }
14956
0
}
14957
14958
//-----------------------------------------------------------------------------
14959
// Docking: ImGuiDockContext Docking/Undocking functions
14960
//-----------------------------------------------------------------------------
14961
// - DockContextQueueDock()
14962
// - DockContextQueueUndockWindow()
14963
// - DockContextQueueUndockNode()
14964
// - DockContextQueueNotifyRemovedNode()
14965
// - DockContextProcessDock()
14966
// - DockContextProcessUndockWindow()
14967
// - DockContextProcessUndockNode()
14968
// - DockContextCalcDropPosForDocking()
14969
//-----------------------------------------------------------------------------
14970
14971
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
14972
0
{
14973
0
    IM_ASSERT(target != payload);
14974
0
    ImGuiDockRequest req;
14975
0
    req.Type = ImGuiDockRequestType_Dock;
14976
0
    req.DockTargetWindow = target;
14977
0
    req.DockTargetNode = target_node;
14978
0
    req.DockPayload = payload;
14979
0
    req.DockSplitDir = split_dir;
14980
0
    req.DockSplitRatio = split_ratio;
14981
0
    req.DockSplitOuter = split_outer;
14982
0
    ctx->DockContext.Requests.push_back(req);
14983
0
}
14984
14985
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
14986
0
{
14987
0
    ImGuiDockRequest req;
14988
0
    req.Type = ImGuiDockRequestType_Undock;
14989
0
    req.UndockTargetWindow = window;
14990
0
    ctx->DockContext.Requests.push_back(req);
14991
0
}
14992
14993
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
14994
0
{
14995
0
    ImGuiDockRequest req;
14996
0
    req.Type = ImGuiDockRequestType_Undock;
14997
0
    req.UndockTargetNode = node;
14998
0
    ctx->DockContext.Requests.push_back(req);
14999
0
}
15000
15001
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15002
0
{
15003
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15004
0
    for (int n = 0; n < dc->Requests.Size; n++)
15005
0
        if (dc->Requests[n].DockTargetNode == node)
15006
0
            dc->Requests[n].Type = ImGuiDockRequestType_None;
15007
0
}
15008
15009
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15010
0
{
15011
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15012
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15013
15014
0
    ImGuiContext& g = *ctx;
15015
0
    IM_UNUSED(g);
15016
15017
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15018
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15019
0
    ImGuiDockNode* node = req->DockTargetNode;
15020
0
    if (payload_window)
15021
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15022
0
    else
15023
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15024
15025
    // Decide which Tab will be selected at the end of the operation
15026
0
    ImGuiID next_selected_id = 0;
15027
0
    ImGuiDockNode* payload_node = NULL;
15028
0
    if (payload_window)
15029
0
    {
15030
0
        payload_node = payload_window->DockNodeAsHost;
15031
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15032
0
        if (payload_node && payload_node->IsLeafNode())
15033
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15034
0
        if (payload_node == NULL)
15035
0
            next_selected_id = payload_window->TabId;
15036
0
    }
15037
15038
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15039
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15040
0
    if (node)
15041
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15042
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15043
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15044
15045
    // Create new node and add existing window to it
15046
0
    if (node == NULL)
15047
0
    {
15048
0
        node = DockContextAddNode(ctx, 0);
15049
0
        node->Pos = target_window->Pos;
15050
0
        node->Size = target_window->Size;
15051
0
        if (target_window->DockNodeAsHost == NULL)
15052
0
        {
15053
0
            DockNodeAddWindow(node, target_window, true);
15054
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15055
0
            target_window->DockIsActive = true;
15056
0
        }
15057
0
    }
15058
15059
0
    ImGuiDir split_dir = req->DockSplitDir;
15060
0
    if (split_dir != ImGuiDir_None)
15061
0
    {
15062
        // Split into two, one side will be our payload node unless we are dropping a loose window
15063
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15064
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15065
0
        const float split_ratio = req->DockSplitRatio;
15066
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15067
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15068
0
        new_node->HostWindow = node->HostWindow;
15069
0
        node = new_node;
15070
0
    }
15071
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15072
15073
0
    if (node != payload_node)
15074
0
    {
15075
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15076
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15077
0
        {
15078
0
            DockNodeAddTabBar(node);
15079
0
            for (int n = 0; n < node->Windows.Size; n++)
15080
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15081
0
        }
15082
15083
0
        if (payload_node != NULL)
15084
0
        {
15085
            // Transfer full payload node (with 1+ child windows or child nodes)
15086
0
            if (payload_node->IsSplitNode())
15087
0
            {
15088
0
                if (node->Windows.Size > 0)
15089
0
                {
15090
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15091
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15092
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15093
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15094
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15095
0
                    if (visible_node->TabBar)
15096
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15097
0
                    DockNodeMoveWindows(node, visible_node);
15098
0
                    DockNodeMoveWindows(visible_node, node);
15099
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15100
0
                }
15101
0
                if (node->IsCentralNode())
15102
0
                {
15103
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15104
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15105
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15106
0
                    IM_ASSERT(last_focused_node != NULL);
15107
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15108
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15109
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15110
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15111
0
                    last_focused_root_node->CentralNode = last_focused_node;
15112
0
                }
15113
15114
0
                IM_ASSERT(node->Windows.Size == 0);
15115
0
                DockNodeMoveChildNodes(node, payload_node);
15116
0
            }
15117
0
            else
15118
0
            {
15119
0
                const ImGuiID payload_dock_id = payload_node->ID;
15120
0
                DockNodeMoveWindows(node, payload_node);
15121
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15122
0
            }
15123
0
            DockContextRemoveNode(ctx, payload_node, true);
15124
0
        }
15125
0
        else if (payload_window)
15126
0
        {
15127
            // Transfer single window
15128
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15129
0
            node->VisibleWindow = payload_window;
15130
0
            DockNodeAddWindow(node, payload_window, true);
15131
0
            if (payload_dock_id != 0)
15132
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15133
0
        }
15134
0
    }
15135
0
    else
15136
0
    {
15137
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15138
0
        node->WantHiddenTabBarUpdate = true;
15139
0
    }
15140
15141
    // Update selection immediately
15142
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15143
0
        tab_bar->NextSelectedTabId = next_selected_id;
15144
0
    MarkIniSettingsDirty();
15145
0
}
15146
15147
// Problem:
15148
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15149
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15150
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15151
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15152
// Solution:
15153
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15154
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15155
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15156
0
{
15157
0
    if (ref_viewport == NULL)
15158
0
        return size;
15159
15160
0
    ImGuiContext& g = *GImGui;
15161
0
    ImVec2 max_size = ImFloor(ref_viewport->WorkSize * 0.90f);
15162
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15163
0
    {
15164
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15165
0
        max_size = ImFloor(monitor->WorkSize * 0.90f);
15166
0
    }
15167
0
    return ImMin(size, max_size);
15168
0
}
15169
15170
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15171
0
{
15172
0
    ImGuiContext& g = *ctx;
15173
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15174
0
    if (window->DockNode)
15175
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15176
0
    else
15177
0
        window->DockId = 0;
15178
0
    window->Collapsed = false;
15179
0
    window->DockIsActive = false;
15180
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15181
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15182
15183
0
    MarkIniSettingsDirty();
15184
0
}
15185
15186
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15187
0
{
15188
0
    ImGuiContext& g = *ctx;
15189
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15190
0
    IM_ASSERT(node->IsLeafNode());
15191
0
    IM_ASSERT(node->Windows.Size >= 1);
15192
15193
0
    if (node->IsRootNode() || node->IsCentralNode())
15194
0
    {
15195
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15196
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15197
0
        new_node->Pos = node->Pos;
15198
0
        new_node->Size = node->Size;
15199
0
        new_node->SizeRef = node->SizeRef;
15200
0
        DockNodeMoveWindows(new_node, node);
15201
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15202
0
        node = new_node;
15203
0
    }
15204
0
    else
15205
0
    {
15206
        // Otherwise extract our node and merge our sibling back into the parent node.
15207
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15208
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15209
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15210
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15211
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15212
0
        node->ParentNode = NULL;
15213
0
    }
15214
0
    for (int n = 0; n < node->Windows.Size; n++)
15215
0
    {
15216
0
        ImGuiWindow* window = node->Windows[n];
15217
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15218
0
        if (window->ParentWindow)
15219
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
15220
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
15221
0
    }
15222
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
15223
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
15224
0
    node->WantMouseMove = true;
15225
0
    MarkIniSettingsDirty();
15226
0
}
15227
15228
// This is mostly used for automation.
15229
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
15230
0
{
15231
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
15232
    // (which would be functionally identical) we only show the outer one. Reflect this here.
15233
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
15234
0
        split_outer = true;
15235
0
    ImGuiDockPreviewData split_data;
15236
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
15237
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
15238
0
        return false;
15239
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
15240
0
    return true;
15241
0
}
15242
15243
//-----------------------------------------------------------------------------
15244
// Docking: ImGuiDockNode
15245
//-----------------------------------------------------------------------------
15246
// - DockNodeGetTabOrder()
15247
// - DockNodeAddWindow()
15248
// - DockNodeRemoveWindow()
15249
// - DockNodeMoveChildNodes()
15250
// - DockNodeMoveWindows()
15251
// - DockNodeApplyPosSizeToWindows()
15252
// - DockNodeHideHostWindow()
15253
// - ImGuiDockNodeFindInfoResults
15254
// - DockNodeFindInfo()
15255
// - DockNodeFindWindowByID()
15256
// - DockNodeUpdateFlagsAndCollapse()
15257
// - DockNodeUpdateHasCentralNodeFlag()
15258
// - DockNodeUpdateVisibleFlag()
15259
// - DockNodeStartMouseMovingWindow()
15260
// - DockNodeUpdate()
15261
// - DockNodeUpdateWindowMenu()
15262
// - DockNodeBeginAmendTabBar()
15263
// - DockNodeEndAmendTabBar()
15264
// - DockNodeUpdateTabBar()
15265
// - DockNodeAddTabBar()
15266
// - DockNodeRemoveTabBar()
15267
// - DockNodeIsDropAllowedOne()
15268
// - DockNodeIsDropAllowed()
15269
// - DockNodeCalcTabBarLayout()
15270
// - DockNodeCalcSplitRects()
15271
// - DockNodeCalcDropRectsAndTestMousePos()
15272
// - DockNodePreviewDockSetup()
15273
// - DockNodePreviewDockRender()
15274
//-----------------------------------------------------------------------------
15275
15276
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
15277
0
{
15278
0
    ID = id;
15279
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
15280
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
15281
0
    TabBar = NULL;
15282
0
    SplitAxis = ImGuiAxis_None;
15283
15284
0
    State = ImGuiDockNodeState_Unknown;
15285
0
    LastBgColor = IM_COL32_WHITE;
15286
0
    HostWindow = VisibleWindow = NULL;
15287
0
    CentralNode = OnlyNodeWithWindows = NULL;
15288
0
    CountNodeWithWindows = 0;
15289
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
15290
0
    LastFocusedNodeId = 0;
15291
0
    SelectedTabId = 0;
15292
0
    WantCloseTabId = 0;
15293
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
15294
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
15295
0
    IsVisible = true;
15296
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
15297
0
    IsBgDrawnThisFrame = false;
15298
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
15299
0
}
15300
15301
ImGuiDockNode::~ImGuiDockNode()
15302
0
{
15303
0
    IM_DELETE(TabBar);
15304
0
    TabBar = NULL;
15305
0
    ChildNodes[0] = ChildNodes[1] = NULL;
15306
0
}
15307
15308
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
15309
0
{
15310
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
15311
0
    if (tab_bar == NULL)
15312
0
        return -1;
15313
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
15314
0
    return tab ? tab_bar->GetTabOrder(tab) : -1;
15315
0
}
15316
15317
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
15318
0
{
15319
0
    window->Hidden = true;
15320
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
15321
0
}
15322
15323
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
15324
0
{
15325
0
    ImGuiContext& g = *GImGui; (void)g;
15326
0
    if (window->DockNode)
15327
0
    {
15328
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
15329
0
        IM_ASSERT(window->DockNode->ID != node->ID);
15330
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
15331
0
    }
15332
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
15333
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15334
15335
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
15336
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
15337
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
15338
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
15339
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
15340
15341
0
    node->Windows.push_back(window);
15342
0
    node->WantHiddenTabBarUpdate = true;
15343
0
    window->DockNode = node;
15344
0
    window->DockId = node->ID;
15345
0
    window->DockIsActive = (node->Windows.Size > 1);
15346
0
    window->DockTabWantClose = false;
15347
15348
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
15349
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
15350
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
15351
0
    {
15352
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
15353
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
15354
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
15355
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
15356
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
15357
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
15358
0
    }
15359
15360
    // Add to tab bar if requested
15361
0
    if (add_to_tab_bar)
15362
0
    {
15363
0
        if (node->TabBar == NULL)
15364
0
        {
15365
0
            DockNodeAddTabBar(node);
15366
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
15367
15368
            // Add existing windows
15369
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
15370
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15371
0
        }
15372
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
15373
0
    }
15374
15375
0
    DockNodeUpdateVisibleFlag(node);
15376
15377
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
15378
0
    if (node->HostWindow)
15379
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
15380
0
}
15381
15382
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
15383
0
{
15384
0
    ImGuiContext& g = *GImGui;
15385
0
    IM_ASSERT(window->DockNode == node);
15386
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
15387
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
15388
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
15389
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15390
15391
0
    window->DockNode = NULL;
15392
0
    window->DockIsActive = window->DockTabWantClose = false;
15393
0
    window->DockId = save_dock_id;
15394
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15395
0
    if (window->ParentWindow)
15396
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
15397
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
15398
15399
    // Remove window
15400
0
    bool erased = false;
15401
0
    for (int n = 0; n < node->Windows.Size; n++)
15402
0
        if (node->Windows[n] == window)
15403
0
        {
15404
0
            node->Windows.erase(node->Windows.Data + n);
15405
0
            erased = true;
15406
0
            break;
15407
0
        }
15408
0
    if (!erased)
15409
0
        IM_ASSERT(erased);
15410
0
    if (node->VisibleWindow == window)
15411
0
        node->VisibleWindow = NULL;
15412
15413
    // Remove tab and possibly tab bar
15414
0
    node->WantHiddenTabBarUpdate = true;
15415
0
    if (node->TabBar)
15416
0
    {
15417
0
        TabBarRemoveTab(node->TabBar, window->TabId);
15418
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
15419
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
15420
0
            DockNodeRemoveTabBar(node);
15421
0
    }
15422
15423
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
15424
0
    {
15425
        // Automatic dock node delete themselves if they are not holding at least one tab
15426
0
        DockContextRemoveNode(&g, node, true);
15427
0
        return;
15428
0
    }
15429
15430
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
15431
0
    {
15432
0
        ImGuiWindow* remaining_window = node->Windows[0];
15433
0
        if (node->HostWindow->ViewportOwned && node->IsRootNode())
15434
0
        {
15435
            // Transfer viewport back to the remaining loose window
15436
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X=>%08X for Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, remaining_window->ID, remaining_window->Name);
15437
0
            IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
15438
0
            node->HostWindow->Viewport->Window = remaining_window;
15439
0
            node->HostWindow->Viewport->ID = remaining_window->ID;
15440
0
        }
15441
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
15442
0
    }
15443
15444
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
15445
0
    DockNodeUpdateVisibleFlag(node);
15446
0
}
15447
15448
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15449
0
{
15450
0
    IM_ASSERT(dst_node->Windows.Size == 0);
15451
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
15452
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
15453
0
    if (dst_node->ChildNodes[0])
15454
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
15455
0
    if (dst_node->ChildNodes[1])
15456
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
15457
0
    dst_node->SplitAxis = src_node->SplitAxis;
15458
0
    dst_node->SizeRef = src_node->SizeRef;
15459
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
15460
0
}
15461
15462
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15463
0
{
15464
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
15465
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
15466
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
15467
0
    if (src_tab_bar != NULL)
15468
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
15469
15470
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
15471
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
15472
0
    if (move_tab_bar)
15473
0
    {
15474
0
        dst_node->TabBar = src_node->TabBar;
15475
0
        src_node->TabBar = NULL;
15476
0
    }
15477
15478
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
15479
0
    for (ImGuiWindow* window : src_node->Windows)
15480
0
    {
15481
0
        window->DockNode = NULL;
15482
0
        window->DockIsActive = false;
15483
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
15484
0
    }
15485
0
    src_node->Windows.clear();
15486
15487
0
    if (!move_tab_bar && src_node->TabBar)
15488
0
    {
15489
0
        if (dst_node->TabBar)
15490
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
15491
0
        DockNodeRemoveTabBar(src_node);
15492
0
    }
15493
0
}
15494
15495
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
15496
0
{
15497
0
    for (int n = 0; n < node->Windows.Size; n++)
15498
0
    {
15499
0
        SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
15500
0
        SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
15501
0
    }
15502
0
}
15503
15504
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
15505
0
{
15506
0
    if (node->HostWindow)
15507
0
    {
15508
0
        if (node->HostWindow->DockNodeAsHost == node)
15509
0
            node->HostWindow->DockNodeAsHost = NULL;
15510
0
        node->HostWindow = NULL;
15511
0
    }
15512
15513
0
    if (node->Windows.Size == 1)
15514
0
    {
15515
0
        node->VisibleWindow = node->Windows[0];
15516
0
        node->Windows[0]->DockIsActive = false;
15517
0
    }
15518
15519
0
    if (node->TabBar)
15520
0
        DockNodeRemoveTabBar(node);
15521
0
}
15522
15523
// Search function called once by root node in DockNodeUpdate()
15524
struct ImGuiDockNodeTreeInfo
15525
{
15526
    ImGuiDockNode*      CentralNode;
15527
    ImGuiDockNode*      FirstNodeWithWindows;
15528
    int                 CountNodesWithWindows;
15529
    //ImGuiWindowClass  WindowClassForMerges;
15530
15531
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
15532
};
15533
15534
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
15535
0
{
15536
0
    if (node->Windows.Size > 0)
15537
0
    {
15538
0
        if (info->FirstNodeWithWindows == NULL)
15539
0
            info->FirstNodeWithWindows = node;
15540
0
        info->CountNodesWithWindows++;
15541
0
    }
15542
0
    if (node->IsCentralNode())
15543
0
    {
15544
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
15545
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
15546
0
        info->CentralNode = node;
15547
0
    }
15548
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
15549
0
        return;
15550
0
    if (node->ChildNodes[0])
15551
0
        DockNodeFindInfo(node->ChildNodes[0], info);
15552
0
    if (node->ChildNodes[1])
15553
0
        DockNodeFindInfo(node->ChildNodes[1], info);
15554
0
}
15555
15556
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
15557
0
{
15558
0
    IM_ASSERT(id != 0);
15559
0
    for (int n = 0; n < node->Windows.Size; n++)
15560
0
        if (node->Windows[n]->ID == id)
15561
0
            return node->Windows[n];
15562
0
    return NULL;
15563
0
}
15564
15565
// - Remove inactive windows/nodes.
15566
// - Update visibility flag.
15567
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
15568
0
{
15569
0
    ImGuiContext& g = *GImGui;
15570
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15571
15572
    // Inherit most flags
15573
0
    if (node->ParentNode)
15574
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
15575
15576
    // Recurse into children
15577
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
15578
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
15579
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
15580
0
    node->HasCentralNodeChild = false;
15581
0
    if (node->ChildNodes[0])
15582
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
15583
0
    if (node->ChildNodes[1])
15584
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
15585
15586
    // Remove inactive windows, collapse nodes
15587
    // Merge node flags overrides stored in windows
15588
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
15589
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15590
0
    {
15591
0
        ImGuiWindow* window = node->Windows[window_n];
15592
0
        IM_ASSERT(window->DockNode == node);
15593
15594
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
15595
0
        bool remove = false;
15596
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
15597
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
15598
0
        remove |= (window->DockTabWantClose);
15599
0
        if (remove)
15600
0
        {
15601
0
            window->DockTabWantClose = false;
15602
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
15603
0
            {
15604
0
                DockNodeHideHostWindow(node);
15605
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15606
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
15607
0
                return;
15608
0
            }
15609
0
            DockNodeRemoveWindow(node, window, node->ID);
15610
0
            window_n--;
15611
0
            continue;
15612
0
        }
15613
15614
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
15615
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
15616
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
15617
0
    }
15618
0
    node->UpdateMergedFlags();
15619
15620
    // Auto-hide tab bar option
15621
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
15622
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
15623
0
        node->WantHiddenTabBarToggle = true;
15624
0
    node->WantHiddenTabBarUpdate = false;
15625
15626
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
15627
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
15628
0
        node->WantHiddenTabBarToggle = false;
15629
15630
    // Apply toggles at a single point of the frame (here!)
15631
0
    if (node->Windows.Size > 1)
15632
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15633
0
    else if (node->WantHiddenTabBarToggle)
15634
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
15635
0
    node->WantHiddenTabBarToggle = false;
15636
15637
0
    DockNodeUpdateVisibleFlag(node);
15638
0
}
15639
15640
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
15641
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
15642
0
{
15643
0
    node->HasCentralNodeChild = false;
15644
0
    if (node->ChildNodes[0])
15645
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
15646
0
    if (node->ChildNodes[1])
15647
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
15648
0
    if (node->IsRootNode())
15649
0
    {
15650
0
        ImGuiDockNode* mark_node = node->CentralNode;
15651
0
        while (mark_node)
15652
0
        {
15653
0
            mark_node->HasCentralNodeChild = true;
15654
0
            mark_node = mark_node->ParentNode;
15655
0
        }
15656
0
    }
15657
0
}
15658
15659
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
15660
0
{
15661
    // Update visibility flag
15662
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
15663
0
    is_visible |= (node->Windows.Size > 0);
15664
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
15665
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
15666
0
    node->IsVisible = is_visible;
15667
0
}
15668
15669
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
15670
0
{
15671
0
    ImGuiContext& g = *GImGui;
15672
0
    IM_ASSERT(node->WantMouseMove == true);
15673
0
    StartMouseMovingWindow(window);
15674
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
15675
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
15676
0
    node->WantMouseMove = false;
15677
0
}
15678
15679
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
15680
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
15681
0
{
15682
0
    DockNodeUpdateFlagsAndCollapse(node);
15683
15684
    // - Setup central node pointers
15685
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
15686
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
15687
0
    ImGuiDockNodeTreeInfo info;
15688
0
    DockNodeFindInfo(node, &info);
15689
0
    node->CentralNode = info.CentralNode;
15690
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
15691
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
15692
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
15693
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
15694
15695
    // Copy the window class from of our first window so it can be used for proper dock filtering.
15696
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
15697
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
15698
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
15699
0
    {
15700
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
15701
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
15702
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
15703
0
            {
15704
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
15705
0
                break;
15706
0
            }
15707
0
    }
15708
15709
0
    ImGuiDockNode* mark_node = node->CentralNode;
15710
0
    while (mark_node)
15711
0
    {
15712
0
        mark_node->HasCentralNodeChild = true;
15713
0
        mark_node = mark_node->ParentNode;
15714
0
    }
15715
0
}
15716
15717
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
15718
0
{
15719
    // Remove ourselves from any previous different host window
15720
    // This can happen if a user mistakenly does (see #4295 for details):
15721
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
15722
    //  - N+1: NewFrame()                   // will create floating host window for that node
15723
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
15724
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
15725
0
        node->HostWindow->DockNodeAsHost = NULL;
15726
15727
0
    host_window->DockNodeAsHost = node;
15728
0
    node->HostWindow = host_window;
15729
0
}
15730
15731
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
15732
0
{
15733
0
    ImGuiContext& g = *GImGui;
15734
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
15735
0
    node->LastFrameAlive = g.FrameCount;
15736
0
    node->IsBgDrawnThisFrame = false;
15737
15738
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
15739
0
    if (node->IsRootNode())
15740
0
        DockNodeUpdateForRootNode(node);
15741
15742
    // Remove tab bar if not needed
15743
0
    if (node->TabBar && node->IsNoTabBar())
15744
0
        DockNodeRemoveTabBar(node);
15745
15746
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
15747
0
    bool want_to_hide_host_window = false;
15748
0
    if (node->IsFloatingNode())
15749
0
    {
15750
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
15751
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
15752
0
                want_to_hide_host_window = true;
15753
0
        if (node->CountNodeWithWindows == 0)
15754
0
            want_to_hide_host_window = true;
15755
0
    }
15756
0
    if (want_to_hide_host_window)
15757
0
    {
15758
0
        if (node->Windows.Size == 1)
15759
0
        {
15760
            // Floating window pos/size is authoritative
15761
0
            ImGuiWindow* single_window = node->Windows[0];
15762
0
            node->Pos = single_window->Pos;
15763
0
            node->Size = single_window->SizeFull;
15764
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
15765
15766
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
15767
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
15768
0
                FocusWindow(single_window);
15769
0
            if (node->HostWindow)
15770
0
            {
15771
0
                single_window->Viewport = node->HostWindow->Viewport;
15772
0
                single_window->ViewportId = node->HostWindow->ViewportId;
15773
0
                if (node->HostWindow->ViewportOwned)
15774
0
                {
15775
0
                    single_window->Viewport->Window = single_window;
15776
0
                    single_window->ViewportOwned = true;
15777
0
                }
15778
0
            }
15779
0
        }
15780
15781
0
        DockNodeHideHostWindow(node);
15782
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15783
0
        node->WantCloseAll = false;
15784
0
        node->WantCloseTabId = 0;
15785
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
15786
0
        node->LastFrameActive = g.FrameCount;
15787
15788
0
        if (node->WantMouseMove && node->Windows.Size == 1)
15789
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
15790
0
        return;
15791
0
    }
15792
15793
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
15794
    // while the expected visible window is resizing itself.
15795
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
15796
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
15797
    //   N+0: Begin(): window created (with no known size), node is created
15798
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
15799
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
15800
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
15801
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
15802
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
15803
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
15804
0
    {
15805
0
        IM_ASSERT(node->Windows.Size > 0);
15806
0
        ImGuiWindow* ref_window = NULL;
15807
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
15808
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
15809
0
        if (ref_window == NULL)
15810
0
            ref_window = node->Windows[0];
15811
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
15812
0
        {
15813
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
15814
0
            return;
15815
0
        }
15816
0
    }
15817
15818
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
15819
15820
    // Decide if the node will have a close button and a window menu button
15821
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
15822
0
    node->HasCloseButton = false;
15823
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15824
0
    {
15825
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
15826
0
        ImGuiWindow* window = node->Windows[window_n];
15827
0
        node->HasCloseButton |= window->HasCloseButton;
15828
0
        window->DockIsActive = (node->Windows.Size > 1);
15829
0
    }
15830
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
15831
0
        node->HasCloseButton = false;
15832
15833
    // Bind or create host window
15834
0
    ImGuiWindow* host_window = NULL;
15835
0
    bool beginned_into_host_window = false;
15836
0
    if (node->IsDockSpace())
15837
0
    {
15838
        // [Explicit root dockspace node]
15839
0
        IM_ASSERT(node->HostWindow);
15840
0
        host_window = node->HostWindow;
15841
0
    }
15842
0
    else
15843
0
    {
15844
        // [Automatic root or child nodes]
15845
0
        if (node->IsRootNode() && node->IsVisible)
15846
0
        {
15847
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
15848
15849
            // Sync Pos
15850
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
15851
0
                SetNextWindowPos(ref_window->Pos);
15852
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
15853
0
                SetNextWindowPos(node->Pos);
15854
15855
            // Sync Size
15856
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
15857
0
                SetNextWindowSize(ref_window->SizeFull);
15858
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
15859
0
                SetNextWindowSize(node->Size);
15860
15861
            // Sync Collapsed
15862
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
15863
0
                SetNextWindowCollapsed(ref_window->Collapsed);
15864
15865
            // Sync Viewport
15866
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
15867
0
                SetNextWindowViewport(ref_window->ViewportId);
15868
15869
0
            SetNextWindowClass(&node->WindowClass);
15870
15871
            // Begin into the host window
15872
0
            char window_label[20];
15873
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
15874
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
15875
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
15876
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
15877
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
15878
15879
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
15880
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
15881
0
            Begin(window_label, NULL, window_flags);
15882
0
            PopStyleVar();
15883
0
            beginned_into_host_window = true;
15884
15885
0
            host_window = g.CurrentWindow;
15886
0
            DockNodeSetupHostWindow(node, host_window);
15887
0
            host_window->DC.CursorPos = host_window->Pos;
15888
0
            node->Pos = host_window->Pos;
15889
0
            node->Size = host_window->Size;
15890
15891
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
15892
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
15893
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
15894
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
15895
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
15896
            // after the dock host window, losing their top-most status.
15897
0
            if (node->HostWindow->Appearing)
15898
0
                BringWindowToDisplayFront(node->HostWindow);
15899
15900
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
15901
0
        }
15902
0
        else if (node->ParentNode)
15903
0
        {
15904
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
15905
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
15906
0
        }
15907
0
        if (node->WantMouseMove && node->HostWindow)
15908
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
15909
0
    }
15910
15911
    // Update focused node (the one whose title bar is highlight) within a node tree
15912
0
    if (node->IsSplitNode())
15913
0
        IM_ASSERT(node->TabBar == NULL);
15914
0
    if (node->IsRootNode())
15915
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
15916
0
            while (p_window != NULL && p_window->DockNode != NULL)
15917
0
            {
15918
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
15919
0
                if (p_node == node)
15920
0
                {
15921
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
15922
0
                    break;
15923
0
                }
15924
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
15925
0
            }
15926
15927
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
15928
0
    ImGuiDockNode* central_node = node->CentralNode;
15929
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
15930
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
15931
0
    if (central_node_hole)
15932
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
15933
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
15934
0
                central_node_hole_register_hit_test_hole = false;
15935
0
    if (central_node_hole_register_hit_test_hole)
15936
0
    {
15937
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
15938
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
15939
        // covering passthru node we'd have a gap on the edge not covered by the hole)
15940
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
15941
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
15942
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
15943
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
15944
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
15945
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
15946
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
15947
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
15948
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
15949
0
        if (central_node_hole && !hole_rect.IsInverted())
15950
0
        {
15951
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
15952
0
            if (host_window->ParentWindow)
15953
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
15954
0
        }
15955
0
    }
15956
15957
    // Update position/size, process and draw resizing splitters
15958
0
    if (node->IsRootNode() && host_window)
15959
0
    {
15960
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
15961
0
        DockNodeTreeUpdateSplitter(node);
15962
0
    }
15963
15964
    // Draw empty node background (currently can only be the Central Node)
15965
0
    if (host_window && node->IsEmpty() && node->IsVisible)
15966
0
    {
15967
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15968
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
15969
0
        if (node->LastBgColor != 0)
15970
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
15971
0
        node->IsBgDrawnThisFrame = true;
15972
0
    }
15973
15974
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
15975
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
15976
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
15977
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
15978
0
    if (render_dockspace_bg && node->IsVisible)
15979
0
    {
15980
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15981
0
        if (central_node_hole)
15982
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
15983
0
        else
15984
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
15985
0
    }
15986
15987
    // Draw and populate Tab Bar
15988
0
    if (host_window)
15989
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
15990
0
    if (host_window && node->Windows.Size > 0)
15991
0
    {
15992
0
        DockNodeUpdateTabBar(node, host_window);
15993
0
    }
15994
0
    else
15995
0
    {
15996
0
        node->WantCloseAll = false;
15997
0
        node->WantCloseTabId = 0;
15998
0
        node->IsFocused = false;
15999
0
    }
16000
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16001
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16002
0
    else if (node->Windows.Size > 0)
16003
0
        node->SelectedTabId = node->Windows[0]->TabId;
16004
16005
    // Draw payload drop target
16006
0
    if (host_window && node->IsVisible)
16007
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16008
0
            BeginDockableDragDropTarget(host_window);
16009
16010
    // We update this after DockNodeUpdateTabBar()
16011
0
    node->LastFrameActive = g.FrameCount;
16012
16013
    // Recurse into children
16014
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16015
0
    if (host_window)
16016
0
    {
16017
0
        if (node->ChildNodes[0])
16018
0
            DockNodeUpdate(node->ChildNodes[0]);
16019
0
        if (node->ChildNodes[1])
16020
0
            DockNodeUpdate(node->ChildNodes[1]);
16021
16022
        // Render outer borders last (after the tab bar)
16023
0
        if (node->IsRootNode())
16024
0
            RenderWindowOuterBorders(host_window);
16025
0
    }
16026
16027
    // End host window
16028
0
    if (beginned_into_host_window) //-V1020
16029
0
        End();
16030
0
}
16031
16032
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16033
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16034
0
{
16035
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16036
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16037
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16038
0
        return d;
16039
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16040
0
}
16041
16042
static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16043
0
{
16044
    // Try to position the menu so it is more likely to stays within the same viewport
16045
0
    ImGuiContext& g = *GImGui;
16046
0
    ImGuiID ret_tab_id = 0;
16047
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16048
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16049
0
    else
16050
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16051
0
    if (BeginPopup("#WindowMenu"))
16052
0
    {
16053
0
        node->IsFocused = true;
16054
0
        if (tab_bar->Tabs.Size == 1)
16055
0
        {
16056
0
            if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16057
0
                node->WantHiddenTabBarToggle = true;
16058
0
        }
16059
0
        else
16060
0
        {
16061
0
            for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16062
0
            {
16063
0
                ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16064
0
                if (tab->Flags & ImGuiTabItemFlags_Button)
16065
0
                    continue;
16066
0
                if (Selectable(tab_bar->GetTabName(tab), tab->ID == tab_bar->SelectedTabId))
16067
0
                    ret_tab_id = tab->ID;
16068
0
                SameLine();
16069
0
                Text("   ");
16070
0
            }
16071
0
        }
16072
0
        EndPopup();
16073
0
    }
16074
0
    return ret_tab_id;
16075
0
}
16076
16077
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16078
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16079
0
{
16080
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16081
0
        return false;
16082
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16083
0
        return false;
16084
0
    Begin(node->HostWindow->Name);
16085
0
    PushOverrideID(node->ID);
16086
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node);
16087
0
    IM_UNUSED(ret);
16088
0
    IM_ASSERT(ret);
16089
0
    return true;
16090
0
}
16091
16092
void ImGui::DockNodeEndAmendTabBar()
16093
0
{
16094
0
    EndTabBar();
16095
0
    PopID();
16096
0
    End();
16097
0
}
16098
16099
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16100
0
{
16101
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16102
0
    ImGuiContext& g = *GImGui;
16103
0
    if (g.NavWindowingTarget)
16104
0
        return (g.NavWindowingTarget->DockNode == node);
16105
16106
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16107
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16108
0
    {
16109
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16110
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16111
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16112
0
            parent_window = parent_window->ParentWindow->RootWindow;
16113
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16114
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16115
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16116
0
                return true;
16117
0
    }
16118
0
    return false;
16119
0
}
16120
16121
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16122
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16123
0
{
16124
0
    ImGuiContext& g = *GImGui;
16125
0
    ImGuiStyle& style = g.Style;
16126
16127
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16128
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16129
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16130
0
    node->WantCloseAll = false;
16131
0
    node->WantCloseTabId = 0;
16132
16133
    // Decide if we should use a focused title bar color
16134
0
    bool is_focused = false;
16135
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16136
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16137
0
        is_focused = true;
16138
16139
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16140
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16141
0
    {
16142
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16143
0
        node->IsFocused = is_focused;
16144
0
        if (is_focused)
16145
0
            node->LastFrameFocused = g.FrameCount;
16146
0
        if (node->VisibleWindow)
16147
0
        {
16148
            // Notify root of visible window (used to display title in OS task bar)
16149
0
            if (is_focused || root_node->VisibleWindow == NULL)
16150
0
                root_node->VisibleWindow = node->VisibleWindow;
16151
0
            if (node->TabBar)
16152
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16153
0
        }
16154
0
        return;
16155
0
    }
16156
16157
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16158
0
    bool backup_skip_item = host_window->SkipItems;
16159
0
    if (!node->IsDockSpace())
16160
0
    {
16161
0
        host_window->SkipItems = false;
16162
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16163
0
    }
16164
16165
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16166
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16167
    // as docked windows themselves will override the stack with their own root ID.
16168
0
    PushOverrideID(node->ID);
16169
0
    ImGuiTabBar* tab_bar = node->TabBar;
16170
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16171
0
    if (tab_bar == NULL)
16172
0
    {
16173
0
        DockNodeAddTabBar(node);
16174
0
        tab_bar = node->TabBar;
16175
0
    }
16176
16177
0
    ImGuiID focus_tab_id = 0;
16178
0
    node->IsFocused = is_focused;
16179
16180
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16181
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16182
16183
    // In a dock node, the Collapse Button turns into the Window Menu button.
16184
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
16185
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
16186
0
    {
16187
0
        if (ImGuiID tab_id = DockNodeUpdateWindowMenu(node, tab_bar))
16188
0
            focus_tab_id = tab_bar->NextSelectedTabId = tab_id;
16189
0
        is_focused |= node->IsFocused;
16190
0
    }
16191
16192
    // Layout
16193
0
    ImRect title_bar_rect, tab_bar_rect;
16194
0
    ImVec2 window_menu_button_pos;
16195
0
    ImVec2 close_button_pos;
16196
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
16197
16198
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
16199
0
    const int tabs_count_old = tab_bar->Tabs.Size;
16200
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16201
0
    {
16202
0
        ImGuiWindow* window = node->Windows[window_n];
16203
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
16204
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
16205
0
    }
16206
16207
    // Title bar
16208
0
    if (is_focused)
16209
0
        node->LastFrameFocused = g.FrameCount;
16210
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
16211
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE);
16212
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
16213
16214
    // Docking/Collapse button
16215
0
    if (has_window_menu_button)
16216
0
    {
16217
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
16218
0
            OpenPopup("#WindowMenu");
16219
0
        if (IsItemActive())
16220
0
            focus_tab_id = tab_bar->SelectedTabId;
16221
0
    }
16222
16223
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
16224
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
16225
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
16226
0
    {
16227
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
16228
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
16229
0
        tabs_unsorted_start = tab_n;
16230
0
    }
16231
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
16232
0
    {
16233
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
16234
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
16235
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
16236
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
16237
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
16238
0
    }
16239
16240
    // Apply NavWindow focus back to the tab bar
16241
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
16242
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
16243
16244
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
16245
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
16246
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
16247
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
16248
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
16249
16250
    // Begin tab bar
16251
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
16252
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
16253
0
    if (!host_window->Collapsed && is_focused)
16254
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
16255
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
16256
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
16257
16258
    // Backup style colors
16259
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
16260
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16261
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
16262
16263
    // Submit actual tabs
16264
0
    node->VisibleWindow = NULL;
16265
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16266
0
    {
16267
0
        ImGuiWindow* window = node->Windows[window_n];
16268
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
16269
0
            continue;
16270
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
16271
0
        {
16272
0
            ImGuiTabItemFlags tab_item_flags = 0;
16273
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
16274
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
16275
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
16276
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
16277
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
16278
16279
            // Apply stored style overrides for the window
16280
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16281
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
16282
16283
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
16284
0
            bool tab_open = true;
16285
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
16286
0
            if (!tab_open)
16287
0
                node->WantCloseTabId = window->TabId;
16288
0
            if (tab_bar->VisibleTabId == window->TabId)
16289
0
                node->VisibleWindow = window;
16290
16291
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
16292
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
16293
0
            window->DockTabItemRect = g.LastItemData.Rect;
16294
16295
            // Update navigation ID on menu layer
16296
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
16297
0
                host_window->NavLastIds[1] = window->TabId;
16298
0
        }
16299
0
    }
16300
16301
    // Restore style colors
16302
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16303
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
16304
16305
    // Notify root of visible window (used to display title in OS task bar)
16306
0
    if (node->VisibleWindow)
16307
0
        if (is_focused || root_node->VisibleWindow == NULL)
16308
0
            root_node->VisibleWindow = node->VisibleWindow;
16309
16310
    // Close button (after VisibleWindow was updated)
16311
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
16312
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
16313
0
    const bool close_button_is_visible = node->HasCloseButton;
16314
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
16315
0
    if (close_button_is_visible)
16316
0
    {
16317
0
        if (!close_button_is_enabled)
16318
0
        {
16319
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
16320
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
16321
0
        }
16322
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
16323
0
        {
16324
0
            node->WantCloseAll = true;
16325
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
16326
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
16327
0
        }
16328
        //if (IsItemActive())
16329
        //    focus_tab_id = tab_bar->SelectedTabId;
16330
0
        if (!close_button_is_enabled)
16331
0
        {
16332
0
            PopStyleColor();
16333
0
            PopItemFlag();
16334
0
        }
16335
0
    }
16336
16337
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
16338
    // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held)
16339
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
16340
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
16341
0
    {
16342
0
        bool held;
16343
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap);
16344
0
        if (g.HoveredId == title_bar_id)
16345
0
        {
16346
            // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar,
16347
            // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
16348
0
            g.LastItemData.ID = title_bar_id;
16349
0
            SetItemAllowOverlap();
16350
0
        }
16351
0
        if (held)
16352
0
        {
16353
0
            if (IsMouseClicked(0))
16354
0
                focus_tab_id = tab_bar->SelectedTabId;
16355
16356
            // Forward moving request to selected window
16357
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
16358
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false);
16359
0
        }
16360
0
    }
16361
16362
    // Forward focus from host node to selected window
16363
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
16364
    //    focus_tab_id = tab_bar->SelectedTabId;
16365
16366
    // When clicked on a tab we requested focus to the docked child
16367
    // This overrides the value set by "forward focus from host node to selected window".
16368
0
    if (tab_bar->NextSelectedTabId)
16369
0
        focus_tab_id = tab_bar->NextSelectedTabId;
16370
16371
    // Apply navigation focus
16372
0
    if (focus_tab_id != 0)
16373
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
16374
0
            if (tab->Window)
16375
0
            {
16376
0
                FocusWindow(tab->Window);
16377
0
                NavInitWindow(tab->Window, false);
16378
0
            }
16379
16380
0
    EndTabBar();
16381
0
    PopID();
16382
16383
    // Restore SkipItems flag
16384
0
    if (!node->IsDockSpace())
16385
0
    {
16386
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
16387
0
        host_window->SkipItems = backup_skip_item;
16388
0
    }
16389
0
}
16390
16391
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
16392
0
{
16393
0
    IM_ASSERT(node->TabBar == NULL);
16394
0
    node->TabBar = IM_NEW(ImGuiTabBar);
16395
0
}
16396
16397
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
16398
0
{
16399
0
    if (node->TabBar == NULL)
16400
0
        return;
16401
0
    IM_DELETE(node->TabBar);
16402
0
    node->TabBar = NULL;
16403
0
}
16404
16405
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
16406
0
{
16407
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
16408
0
        return false;
16409
16410
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
16411
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
16412
0
    if (host_class->ClassId != payload_class->ClassId)
16413
0
    {
16414
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
16415
0
            return true;
16416
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
16417
0
            return true;
16418
0
        return false;
16419
0
    }
16420
16421
    // Prevent docking any window created above a popup
16422
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
16423
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
16424
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
16425
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
16426
0
    ImGuiContext& g = *GImGui;
16427
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
16428
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
16429
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
16430
0
                return false;
16431
16432
0
    return true;
16433
0
}
16434
16435
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
16436
0
{
16437
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
16438
0
        return true;
16439
16440
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
16441
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
16442
0
    {
16443
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
16444
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
16445
0
            return true;
16446
0
    }
16447
0
    return false;
16448
0
}
16449
16450
// window menu button == collapse button when not in a dock node.
16451
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
16452
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
16453
0
{
16454
0
    ImGuiContext& g = *GImGui;
16455
0
    ImGuiStyle& style = g.Style;
16456
16457
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
16458
0
    if (out_title_rect) { *out_title_rect = r; }
16459
16460
0
    r.Min.x += style.WindowBorderSize;
16461
0
    r.Max.x -= style.WindowBorderSize;
16462
16463
0
    float button_sz = g.FontSize;
16464
16465
0
    ImVec2 window_menu_button_pos = r.Min;
16466
0
    r.Min.x += style.FramePadding.x;
16467
0
    r.Max.x -= style.FramePadding.x;
16468
0
    if (node->HasCloseButton)
16469
0
    {
16470
0
        r.Max.x -= button_sz;
16471
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - style.FramePadding.x, r.Min.y);
16472
0
    }
16473
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
16474
0
    {
16475
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
16476
0
    }
16477
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
16478
0
    {
16479
0
        r.Max.x -= button_sz + style.FramePadding.x;
16480
0
        window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
16481
0
    }
16482
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
16483
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
16484
0
}
16485
16486
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
16487
0
{
16488
0
    ImGuiContext& g = *GImGui;
16489
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
16490
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16491
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
16492
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
16493
16494
    // Distribute size on given axis (with a desired size or equally)
16495
0
    const float w_avail = size_old[axis] - dock_spacing;
16496
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
16497
0
    {
16498
0
        size_new[axis] = size_new_desired[axis];
16499
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16500
0
    }
16501
0
    else
16502
0
    {
16503
0
        size_new[axis] = IM_FLOOR(w_avail * 0.5f);
16504
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16505
0
    }
16506
16507
    // Position each node
16508
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
16509
0
    {
16510
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
16511
0
    }
16512
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
16513
0
    {
16514
0
        pos_new[axis] = pos_old[axis];
16515
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
16516
0
    }
16517
0
}
16518
16519
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
16520
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
16521
0
{
16522
0
    ImGuiContext& g = *GImGui;
16523
16524
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
16525
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
16526
0
    float hs_w; // Half-size, longer axis
16527
0
    float hs_h; // Half-size, smaller axis
16528
0
    ImVec2 off; // Distance from edge or center
16529
0
    if (outer_docking)
16530
0
    {
16531
        //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
16532
        //hs_h = ImFloor(hs_w * 0.15f);
16533
        //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
16534
0
        hs_w = ImFloor(hs_for_central_nodes * 1.50f);
16535
0
        hs_h = ImFloor(hs_for_central_nodes * 0.80f);
16536
0
        off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h));
16537
0
    }
16538
0
    else
16539
0
    {
16540
0
        hs_w = ImFloor(hs_for_central_nodes);
16541
0
        hs_h = ImFloor(hs_for_central_nodes * 0.90f);
16542
0
        off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
16543
0
    }
16544
16545
0
    ImVec2 c = ImFloor(parent.GetCenter());
16546
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
16547
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
16548
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
16549
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
16550
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
16551
16552
0
    if (test_mouse_pos == NULL)
16553
0
        return false;
16554
16555
0
    ImRect hit_r = out_r;
16556
0
    if (!outer_docking)
16557
0
    {
16558
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
16559
0
        hit_r.Expand(ImFloor(hs_w * 0.30f));
16560
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
16561
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
16562
0
        float r_threshold_center = hs_w * 1.4f;
16563
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
16564
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
16565
0
            return (dir == ImGuiDir_None);
16566
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
16567
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
16568
0
    }
16569
0
    return hit_r.Contains(*test_mouse_pos);
16570
0
}
16571
16572
// host_node may be NULL if the window doesn't have a DockNode already.
16573
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
16574
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
16575
0
{
16576
0
    ImGuiContext& g = *GImGui;
16577
16578
    // There is an edge case when docking into a dockspace which only has inactive nodes.
16579
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
16580
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
16581
0
    if (payload_node == NULL)
16582
0
        payload_node = payload_window->DockNodeAsHost;
16583
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
16584
0
    if (ref_node_for_rect)
16585
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
16586
16587
    // Filter, figure out where we are allowed to dock
16588
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
16589
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
16590
0
    data->IsCenterAvailable = true;
16591
0
    if (is_outer_docking)
16592
0
        data->IsCenterAvailable = false;
16593
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking)
16594
0
        data->IsCenterAvailable = false;
16595
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
16596
0
        data->IsCenterAvailable = false;
16597
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
16598
0
        data->IsCenterAvailable = false;
16599
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
16600
0
        data->IsCenterAvailable = false;
16601
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
16602
0
        data->IsCenterAvailable = false;
16603
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
16604
0
        data->IsCenterAvailable = false;
16605
16606
0
    data->IsSidesAvailable = true;
16607
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit)
16608
0
        data->IsSidesAvailable = false;
16609
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
16610
0
        data->IsSidesAvailable = false;
16611
0
    else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther))
16612
0
        data->IsSidesAvailable = false;
16613
16614
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
16615
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
16616
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
16617
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
16618
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
16619
16620
    // Calculate drop shapes geometry for allowed splitting directions
16621
0
    IM_ASSERT(ImGuiDir_None == -1);
16622
0
    data->SplitNode = host_node;
16623
0
    data->SplitDir = ImGuiDir_None;
16624
0
    data->IsSplitDirExplicit = false;
16625
0
    if (!host_window->Collapsed)
16626
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16627
0
        {
16628
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
16629
0
                continue;
16630
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
16631
0
                continue;
16632
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
16633
0
            {
16634
0
                data->SplitDir = (ImGuiDir)dir;
16635
0
                data->IsSplitDirExplicit = true;
16636
0
            }
16637
0
        }
16638
16639
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
16640
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
16641
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
16642
0
        data->IsDropAllowed = false;
16643
16644
    // Calculate split area
16645
0
    data->SplitRatio = 0.0f;
16646
0
    if (data->SplitDir != ImGuiDir_None)
16647
0
    {
16648
0
        ImGuiDir split_dir = data->SplitDir;
16649
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16650
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
16651
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
16652
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
16653
16654
        // Calculate split ratio so we can pass it down the docking request
16655
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
16656
0
        data->FutureNode.Pos = pos_new;
16657
0
        data->FutureNode.Size = size_new;
16658
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
16659
0
    }
16660
0
}
16661
16662
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
16663
0
{
16664
0
    ImGuiContext& g = *GImGui;
16665
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
16666
16667
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
16668
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
16669
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
16670
16671
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
16672
0
    int overlay_draw_lists_count = 0;
16673
0
    ImDrawList* overlay_draw_lists[2];
16674
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
16675
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
16676
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
16677
16678
    // Draw main preview rectangle
16679
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
16680
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
16681
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
16682
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
16683
16684
    // Display area preview
16685
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
16686
0
    if (data->IsDropAllowed)
16687
0
    {
16688
0
        ImRect overlay_rect = data->FutureNode.Rect();
16689
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
16690
0
            overlay_rect.Min.y += GetFrameHeight();
16691
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
16692
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16693
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE));
16694
0
    }
16695
16696
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
16697
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
16698
0
    {
16699
        // Compute target tab bar geometry so we can locate our preview tabs
16700
0
        ImRect tab_bar_rect;
16701
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
16702
0
        ImVec2 tab_pos = tab_bar_rect.Min;
16703
0
        if (host_node && host_node->TabBar)
16704
0
        {
16705
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
16706
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
16707
0
            else
16708
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
16709
0
        }
16710
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
16711
0
        {
16712
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
16713
0
        }
16714
16715
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
16716
0
        if (root_payload->DockNodeAsHost)
16717
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
16718
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
16719
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
16720
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
16721
0
        {
16722
            // DockNode's TabBar may have non-window Tabs manually appended by user
16723
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
16724
0
            if (tab_bar_with_payload && payload_window == NULL)
16725
0
                continue;
16726
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
16727
0
                continue;
16728
16729
            // Calculate the tab bounding box for each payload window
16730
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
16731
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
16732
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
16733
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
16734
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
16735
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
16736
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16737
0
            {
16738
0
                ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
16739
0
                if (!tab_bar_rect.Contains(tab_bb))
16740
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
16741
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
16742
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
16743
0
                if (!tab_bar_rect.Contains(tab_bb))
16744
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
16745
0
            }
16746
0
            PopStyleColor();
16747
0
        }
16748
0
    }
16749
16750
    // Display drop boxes
16751
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
16752
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16753
0
    {
16754
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
16755
0
        {
16756
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
16757
0
            ImRect draw_r_in = draw_r;
16758
0
            draw_r_in.Expand(-2.0f);
16759
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
16760
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16761
0
            {
16762
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
16763
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
16764
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
16765
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
16766
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
16767
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
16768
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
16769
0
            }
16770
0
        }
16771
16772
        // Stop after ImGuiDir_None
16773
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
16774
0
            return;
16775
0
    }
16776
0
}
16777
16778
//-----------------------------------------------------------------------------
16779
// Docking: ImGuiDockNode Tree manipulation functions
16780
//-----------------------------------------------------------------------------
16781
// - DockNodeTreeSplit()
16782
// - DockNodeTreeMerge()
16783
// - DockNodeTreeUpdatePosSize()
16784
// - DockNodeTreeUpdateSplitterFindTouchingNode()
16785
// - DockNodeTreeUpdateSplitter()
16786
// - DockNodeTreeFindFallbackLeafNode()
16787
// - DockNodeTreeFindNodeByPos()
16788
//-----------------------------------------------------------------------------
16789
16790
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
16791
0
{
16792
0
    ImGuiContext& g = *GImGui;
16793
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
16794
16795
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
16796
0
    child_0->ParentNode = parent_node;
16797
16798
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
16799
0
    child_1->ParentNode = parent_node;
16800
16801
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
16802
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
16803
0
    parent_node->ChildNodes[0] = child_0;
16804
0
    parent_node->ChildNodes[1] = child_1;
16805
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
16806
0
    parent_node->SplitAxis = split_axis;
16807
0
    parent_node->VisibleWindow = NULL;
16808
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16809
16810
0
    float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE);
16811
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
16812
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
16813
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
16814
0
    child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
16815
0
    child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
16816
16817
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
16818
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
16819
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
16820
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
16821
16822
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
16823
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16824
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16825
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16826
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16827
0
    child_0->UpdateMergedFlags();
16828
0
    child_1->UpdateMergedFlags();
16829
0
    parent_node->UpdateMergedFlags();
16830
0
    if (child_inheritor->IsCentralNode())
16831
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
16832
0
}
16833
16834
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
16835
0
{
16836
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
16837
0
    ImGuiContext& g = *GImGui;
16838
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
16839
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
16840
0
    IM_ASSERT(child_0 || child_1);
16841
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
16842
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
16843
0
    {
16844
0
        IM_ASSERT(parent_node->TabBar == NULL);
16845
0
        IM_ASSERT(parent_node->Windows.Size == 0);
16846
0
    }
16847
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
16848
16849
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
16850
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
16851
0
    if (child_0)
16852
0
    {
16853
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
16854
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
16855
0
    }
16856
0
    if (child_1)
16857
0
    {
16858
0
        DockNodeMoveWindows(parent_node, child_1);
16859
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
16860
0
    }
16861
0
    DockNodeApplyPosSizeToWindows(parent_node);
16862
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16863
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
16864
0
    parent_node->SizeRef = backup_last_explicit_size;
16865
16866
    // Flags transfer
16867
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
16868
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16869
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16870
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
16871
0
    parent_node->UpdateMergedFlags();
16872
16873
0
    if (child_0)
16874
0
    {
16875
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
16876
0
        IM_DELETE(child_0);
16877
0
    }
16878
0
    if (child_1)
16879
0
    {
16880
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
16881
0
        IM_DELETE(child_1);
16882
0
    }
16883
0
}
16884
16885
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
16886
// (Depth-first, Pre-Order)
16887
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
16888
0
{
16889
    // During the regular dock node update we write to all nodes.
16890
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
16891
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
16892
0
    if (write_to_node)
16893
0
    {
16894
0
        node->Pos = pos;
16895
0
        node->Size = size;
16896
0
    }
16897
16898
0
    if (node->IsLeafNode())
16899
0
        return;
16900
16901
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
16902
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
16903
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
16904
0
    ImVec2 child_0_size = size, child_1_size = size;
16905
16906
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
16907
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
16908
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
16909
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
16910
16911
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
16912
0
    {
16913
0
        ImGuiContext& g = *GImGui;
16914
0
        const float spacing = DOCKING_SPLITTER_SIZE;
16915
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
16916
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
16917
16918
        // Size allocation policy
16919
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
16920
0
        const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
16921
16922
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
16923
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImFloor()
16924
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
16925
16926
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
16927
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
16928
0
        {
16929
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
16930
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
16931
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
16932
0
        }
16933
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
16934
0
        {
16935
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
16936
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
16937
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
16938
0
        }
16939
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
16940
0
        {
16941
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
16942
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
16943
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
16944
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * split_ratio);
16945
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
16946
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
16947
0
        }
16948
16949
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
16950
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
16951
0
        {
16952
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
16953
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
16954
0
        }
16955
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
16956
0
        {
16957
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
16958
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
16959
0
        }
16960
0
        else
16961
0
        {
16962
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
16963
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
16964
0
            child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5f));
16965
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
16966
0
        }
16967
16968
0
        child_1_pos[axis] += spacing + child_0_size[axis];
16969
0
    }
16970
16971
0
    if (only_write_to_single_node == NULL)
16972
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
16973
16974
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
16975
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
16976
0
    if (child_0_recurse)
16977
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
16978
0
    if (child_1_recurse)
16979
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
16980
0
}
16981
16982
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
16983
0
{
16984
0
    if (node->IsLeafNode())
16985
0
    {
16986
0
        touching_nodes->push_back(node);
16987
0
        return;
16988
0
    }
16989
0
    if (node->ChildNodes[0]->IsVisible)
16990
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
16991
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
16992
0
    if (node->ChildNodes[1]->IsVisible)
16993
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
16994
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
16995
0
}
16996
16997
// (Depth-First, Pre-Order)
16998
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
16999
0
{
17000
0
    if (node->IsLeafNode())
17001
0
        return;
17002
17003
0
    ImGuiContext& g = *GImGui;
17004
17005
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17006
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17007
0
    if (child_0->IsVisible && child_1->IsVisible)
17008
0
    {
17009
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17010
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17011
0
        IM_ASSERT(axis != ImGuiAxis_None);
17012
0
        ImRect bb;
17013
0
        bb.Min = child_0->Pos;
17014
0
        bb.Max = child_1->Pos;
17015
0
        bb.Min[axis] += child_0->Size[axis];
17016
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17017
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17018
17019
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17020
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17021
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17022
0
        {
17023
0
            ImGuiWindow* window = g.CurrentWindow;
17024
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17025
0
        }
17026
0
        else
17027
0
        {
17028
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17029
            //bb.Max[axis] -= 1;
17030
0
            PushID(node->ID);
17031
17032
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17033
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17034
0
            float min_size = g.Style.WindowMinSize[axis];
17035
0
            float resize_limits[2];
17036
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17037
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17038
17039
0
            ImGuiID splitter_id = GetID("##Splitter");
17040
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17041
0
            {
17042
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17043
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17044
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17045
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17046
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17047
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17048
17049
                // [DEBUG] Render touching nodes & limits
17050
                /*
17051
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17052
                for (int n = 0; n < 2; n++)
17053
                {
17054
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17055
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17056
                    if (axis == ImGuiAxis_X)
17057
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17058
                    else
17059
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17060
                }
17061
                */
17062
0
            }
17063
17064
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17065
0
            float cur_size_0 = child_0->Size[axis];
17066
0
            float cur_size_1 = child_1->Size[axis];
17067
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17068
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17069
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17070
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17071
0
            {
17072
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17073
0
                {
17074
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17075
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17076
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17077
17078
                    // Lock the size of every node that is a sibling of the node we are touching
17079
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17080
0
                    for (int side_n = 0; side_n < 2; side_n++)
17081
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17082
0
                        {
17083
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17084
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17085
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17086
0
                            while (touching_node->ParentNode != node)
17087
0
                            {
17088
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17089
0
                                {
17090
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17091
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17092
0
                                    node_to_preserve->WantLockSizeOnce = true;
17093
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17094
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17095
0
                                }
17096
0
                                touching_node = touching_node->ParentNode;
17097
0
                            }
17098
0
                        }
17099
17100
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17101
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17102
0
                    MarkIniSettingsDirty();
17103
0
                }
17104
0
            }
17105
0
            PopID();
17106
0
        }
17107
0
    }
17108
17109
0
    if (child_0->IsVisible)
17110
0
        DockNodeTreeUpdateSplitter(child_0);
17111
0
    if (child_1->IsVisible)
17112
0
        DockNodeTreeUpdateSplitter(child_1);
17113
0
}
17114
17115
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17116
0
{
17117
0
    if (node->IsLeafNode())
17118
0
        return node;
17119
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17120
0
        return leaf_node;
17121
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17122
0
        return leaf_node;
17123
0
    return NULL;
17124
0
}
17125
17126
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17127
0
{
17128
0
    if (!node->IsVisible)
17129
0
        return NULL;
17130
17131
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17132
0
    ImRect r(node->Pos, node->Pos + node->Size);
17133
0
    r.Expand(dock_spacing * 0.5f);
17134
0
    bool inside = r.Contains(pos);
17135
0
    if (!inside)
17136
0
        return NULL;
17137
17138
0
    if (node->IsLeafNode())
17139
0
        return node;
17140
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17141
0
        return hovered_node;
17142
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17143
0
        return hovered_node;
17144
17145
    // This means we are hovering over the splitter/spacing of a parent node
17146
0
    return node;
17147
0
}
17148
17149
//-----------------------------------------------------------------------------
17150
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17151
//-----------------------------------------------------------------------------
17152
// - SetWindowDock() [Internal]
17153
// - DockSpace()
17154
// - DockSpaceOverViewport()
17155
//-----------------------------------------------------------------------------
17156
17157
// [Internal] Called via SetNextWindowDockID()
17158
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17159
0
{
17160
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17161
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17162
0
        return;
17163
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17164
17165
0
    if (window->DockId == dock_id)
17166
0
        return;
17167
17168
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17169
0
    ImGuiContext* ctx = GImGui;
17170
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17171
0
        if (new_node->IsSplitNode())
17172
0
        {
17173
            // Policy: Find central node or latest focused node. We first move back to our root node.
17174
0
            new_node = DockNodeGetRootNode(new_node);
17175
0
            if (new_node->CentralNode)
17176
0
            {
17177
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
17178
0
                dock_id = new_node->CentralNode->ID;
17179
0
            }
17180
0
            else
17181
0
            {
17182
0
                dock_id = new_node->LastFocusedNodeId;
17183
0
            }
17184
0
        }
17185
17186
0
    if (window->DockId == dock_id)
17187
0
        return;
17188
17189
0
    if (window->DockNode)
17190
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
17191
0
    window->DockId = dock_id;
17192
0
}
17193
17194
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
17195
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
17196
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
17197
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
17198
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
17199
0
{
17200
0
    ImGuiContext* ctx = GImGui;
17201
0
    ImGuiContext& g = *ctx;
17202
0
    ImGuiWindow* window = GetCurrentWindowRead();
17203
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17204
0
        return 0;
17205
17206
    // Early out if parent window is hidden/collapsed
17207
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
17208
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
17209
0
    if (window->SkipItems)
17210
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
17211
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
17212
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
17213
17214
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
17215
0
    IM_ASSERT(id != 0);
17216
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
17217
0
    if (!node)
17218
0
    {
17219
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
17220
0
        node = DockContextAddNode(ctx, id);
17221
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
17222
0
    }
17223
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
17224
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
17225
0
    node->SharedFlags = flags;
17226
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
17227
17228
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
17229
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
17230
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
17231
0
    {
17232
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
17233
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17234
0
        return id;
17235
0
    }
17236
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17237
17238
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
17239
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
17240
0
    {
17241
0
        node->LastFrameAlive = g.FrameCount;
17242
0
        return id;
17243
0
    }
17244
17245
0
    const ImVec2 content_avail = GetContentRegionAvail();
17246
0
    ImVec2 size = ImFloor(size_arg);
17247
0
    if (size.x <= 0.0f)
17248
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
17249
0
    if (size.y <= 0.0f)
17250
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
17251
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17252
17253
0
    node->Pos = window->DC.CursorPos;
17254
0
    node->Size = node->SizeRef = size;
17255
0
    SetNextWindowPos(node->Pos);
17256
0
    SetNextWindowSize(node->Size);
17257
0
    g.NextWindowData.PosUndock = false;
17258
17259
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
17260
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
17261
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
17262
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
17263
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
17264
0
    window_flags |= ImGuiWindowFlags_NoBackground;
17265
17266
0
    char title[256];
17267
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
17268
17269
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
17270
0
    Begin(title, NULL, window_flags);
17271
0
    PopStyleVar();
17272
17273
0
    ImGuiWindow* host_window = g.CurrentWindow;
17274
0
    DockNodeSetupHostWindow(node, host_window);
17275
0
    host_window->ChildId = window->GetID(title);
17276
0
    node->OnlyNodeWithWindows = NULL;
17277
17278
0
    IM_ASSERT(node->IsRootNode());
17279
17280
    // We need to handle the rare case were a central node is missing.
17281
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
17282
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
17283
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
17284
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
17285
    // as it doesn't make sense for an empty dockspace to not have this property.
17286
0
    if (node->IsLeafNode() && !node->IsCentralNode())
17287
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17288
17289
    // Update the node
17290
0
    DockNodeUpdate(node);
17291
17292
0
    End();
17293
0
    ItemSize(size);
17294
0
    return id;
17295
0
}
17296
17297
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
17298
// The limitation with this call is that your window won't have a menu bar.
17299
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
17300
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
17301
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
17302
0
{
17303
0
    if (viewport == NULL)
17304
0
        viewport = GetMainViewport();
17305
17306
0
    SetNextWindowPos(viewport->WorkPos);
17307
0
    SetNextWindowSize(viewport->WorkSize);
17308
0
    SetNextWindowViewport(viewport->ID);
17309
17310
0
    ImGuiWindowFlags host_window_flags = 0;
17311
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
17312
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
17313
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
17314
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
17315
17316
0
    char label[32];
17317
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
17318
17319
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
17320
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
17321
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
17322
0
    Begin(label, NULL, host_window_flags);
17323
0
    PopStyleVar(3);
17324
17325
0
    ImGuiID dockspace_id = GetID("DockSpace");
17326
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
17327
0
    End();
17328
17329
0
    return dockspace_id;
17330
0
}
17331
17332
//-----------------------------------------------------------------------------
17333
// Docking: Builder Functions
17334
//-----------------------------------------------------------------------------
17335
// Very early end-user API to manipulate dock nodes.
17336
// Only available in imgui_internal.h. Expect this API to change/break!
17337
// It is expected that those functions are all called _before_ the dockspace node submission.
17338
//-----------------------------------------------------------------------------
17339
// - DockBuilderDockWindow()
17340
// - DockBuilderGetNode()
17341
// - DockBuilderSetNodePos()
17342
// - DockBuilderSetNodeSize()
17343
// - DockBuilderAddNode()
17344
// - DockBuilderRemoveNode()
17345
// - DockBuilderRemoveNodeChildNodes()
17346
// - DockBuilderRemoveNodeDockedWindows()
17347
// - DockBuilderSplitNode()
17348
// - DockBuilderCopyNodeRec()
17349
// - DockBuilderCopyNode()
17350
// - DockBuilderCopyWindowSettings()
17351
// - DockBuilderCopyDockSpace()
17352
// - DockBuilderFinish()
17353
//-----------------------------------------------------------------------------
17354
17355
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
17356
0
{
17357
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
17358
0
    ImGuiID window_id = ImHashStr(window_name);
17359
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
17360
0
    {
17361
        // Apply to created window
17362
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
17363
0
        window->DockOrder = -1;
17364
0
    }
17365
0
    else
17366
0
    {
17367
        // Apply to settings
17368
0
        ImGuiWindowSettings* settings = FindWindowSettings(window_id);
17369
0
        if (settings == NULL)
17370
0
            settings = CreateNewWindowSettings(window_name);
17371
0
        settings->DockId = node_id;
17372
0
        settings->DockOrder = -1;
17373
0
    }
17374
0
}
17375
17376
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
17377
0
{
17378
0
    ImGuiContext* ctx = GImGui;
17379
0
    return DockContextFindNodeByID(ctx, node_id);
17380
0
}
17381
17382
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
17383
0
{
17384
0
    ImGuiContext* ctx = GImGui;
17385
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17386
0
    if (node == NULL)
17387
0
        return;
17388
0
    node->Pos = pos;
17389
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
17390
0
}
17391
17392
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
17393
0
{
17394
0
    ImGuiContext* ctx = GImGui;
17395
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17396
0
    if (node == NULL)
17397
0
        return;
17398
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17399
0
    node->Size = node->SizeRef = size;
17400
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17401
0
}
17402
17403
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
17404
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
17405
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
17406
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
17407
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
17408
// - Use (id == 0) to let the system allocate a node identifier.
17409
// - Existing node with a same id will be removed.
17410
ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags)
17411
0
{
17412
0
    ImGuiContext* ctx = GImGui;
17413
17414
0
    if (id != 0)
17415
0
        DockBuilderRemoveNode(id);
17416
17417
0
    ImGuiDockNode* node = NULL;
17418
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
17419
0
    {
17420
0
        DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
17421
0
        node = DockContextFindNodeByID(ctx, id);
17422
0
    }
17423
0
    else
17424
0
    {
17425
0
        node = DockContextAddNode(ctx, id);
17426
0
        node->SetLocalFlags(flags);
17427
0
    }
17428
0
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
17429
0
    return node->ID;
17430
0
}
17431
17432
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
17433
0
{
17434
0
    ImGuiContext* ctx = GImGui;
17435
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17436
0
    if (node == NULL)
17437
0
        return;
17438
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
17439
0
    DockBuilderRemoveNodeChildNodes(node_id);
17440
    // Node may have moved or deleted if e.g. any merge happened
17441
0
    node = DockContextFindNodeByID(ctx, node_id);
17442
0
    if (node == NULL)
17443
0
        return;
17444
0
    if (node->IsCentralNode() && node->ParentNode)
17445
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17446
0
    DockContextRemoveNode(ctx, node, true);
17447
0
}
17448
17449
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
17450
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
17451
0
{
17452
0
    ImGuiContext* ctx = GImGui;
17453
0
    ImGuiDockContext* dc  = &ctx->DockContext;
17454
17455
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
17456
0
    if (root_id && root_node == NULL)
17457
0
        return;
17458
0
    bool has_central_node = false;
17459
17460
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
17461
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
17462
17463
    // Process active windows
17464
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
17465
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
17466
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17467
0
        {
17468
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
17469
0
            if (want_removal)
17470
0
            {
17471
0
                if (node->IsCentralNode())
17472
0
                    has_central_node = true;
17473
0
                if (root_id != 0)
17474
0
                    DockContextQueueNotifyRemovedNode(ctx, node);
17475
0
                if (root_node)
17476
0
                {
17477
0
                    DockNodeMoveWindows(root_node, node);
17478
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
17479
0
                }
17480
0
                nodes_to_remove.push_back(node);
17481
0
            }
17482
0
        }
17483
17484
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
17485
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
17486
0
    if (root_node)
17487
0
    {
17488
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
17489
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
17490
0
    }
17491
17492
    // Apply to settings
17493
0
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
17494
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
17495
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
17496
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
17497
0
                {
17498
0
                    settings->DockId = root_id;
17499
0
                    break;
17500
0
                }
17501
17502
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
17503
0
    if (nodes_to_remove.Size > 1)
17504
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
17505
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
17506
0
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
17507
17508
0
    if (root_id == 0)
17509
0
    {
17510
0
        dc->Nodes.Clear();
17511
0
        dc->Requests.clear();
17512
0
    }
17513
0
    else if (has_central_node)
17514
0
    {
17515
0
        root_node->CentralNode = root_node;
17516
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17517
0
    }
17518
0
}
17519
17520
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
17521
0
{
17522
    // Clear references in settings
17523
0
    ImGuiContext* ctx = GImGui;
17524
0
    ImGuiContext& g = *ctx;
17525
0
    if (clear_settings_refs)
17526
0
    {
17527
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17528
0
        {
17529
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
17530
0
            if (!want_removal && settings->DockId != 0)
17531
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
17532
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
17533
0
                        want_removal = true;
17534
0
            if (want_removal)
17535
0
                settings->DockId = 0;
17536
0
        }
17537
0
    }
17538
17539
    // Clear references in windows
17540
0
    for (int n = 0; n < g.Windows.Size; n++)
17541
0
    {
17542
0
        ImGuiWindow* window = g.Windows[n];
17543
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
17544
0
        if (want_removal)
17545
0
        {
17546
0
            const ImGuiID backup_dock_id = window->DockId;
17547
0
            IM_UNUSED(backup_dock_id);
17548
0
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
17549
0
            if (!clear_settings_refs)
17550
0
                IM_ASSERT(window->DockId == backup_dock_id);
17551
0
        }
17552
0
    }
17553
0
}
17554
17555
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
17556
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
17557
// FIXME-DOCK: We are not exposing nor using split_outer.
17558
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
17559
0
{
17560
0
    ImGuiContext& g = *GImGui;
17561
0
    IM_ASSERT(split_dir != ImGuiDir_None);
17562
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
17563
17564
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
17565
0
    if (node == NULL)
17566
0
    {
17567
0
        IM_ASSERT(node != NULL);
17568
0
        return 0;
17569
0
    }
17570
17571
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
17572
17573
0
    ImGuiDockRequest req;
17574
0
    req.Type = ImGuiDockRequestType_Split;
17575
0
    req.DockTargetWindow = NULL;
17576
0
    req.DockTargetNode = node;
17577
0
    req.DockPayload = NULL;
17578
0
    req.DockSplitDir = split_dir;
17579
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
17580
0
    req.DockSplitOuter = false;
17581
0
    DockContextProcessDock(&g, &req);
17582
17583
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
17584
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
17585
0
    if (out_id_at_dir)
17586
0
        *out_id_at_dir = id_at_dir;
17587
0
    if (out_id_at_opposite_dir)
17588
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
17589
0
    return id_at_dir;
17590
0
}
17591
17592
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
17593
0
{
17594
0
    ImGuiContext& g = *GImGui;
17595
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
17596
0
    dst_node->SharedFlags = src_node->SharedFlags;
17597
0
    dst_node->LocalFlags = src_node->LocalFlags;
17598
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17599
0
    dst_node->Pos = src_node->Pos;
17600
0
    dst_node->Size = src_node->Size;
17601
0
    dst_node->SizeRef = src_node->SizeRef;
17602
0
    dst_node->SplitAxis = src_node->SplitAxis;
17603
0
    dst_node->UpdateMergedFlags();
17604
17605
0
    out_node_remap_pairs->push_back(src_node->ID);
17606
0
    out_node_remap_pairs->push_back(dst_node->ID);
17607
17608
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
17609
0
        if (src_node->ChildNodes[child_n])
17610
0
        {
17611
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
17612
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
17613
0
        }
17614
17615
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
17616
0
    return dst_node;
17617
0
}
17618
17619
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
17620
0
{
17621
0
    ImGuiContext* ctx = GImGui;
17622
0
    IM_ASSERT(src_node_id != 0);
17623
0
    IM_ASSERT(dst_node_id != 0);
17624
0
    IM_ASSERT(out_node_remap_pairs != NULL);
17625
17626
0
    DockBuilderRemoveNode(dst_node_id);
17627
17628
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
17629
0
    IM_ASSERT(src_node != NULL);
17630
17631
0
    out_node_remap_pairs->clear();
17632
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
17633
17634
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
17635
0
}
17636
17637
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
17638
0
{
17639
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
17640
0
    if (src_window == NULL)
17641
0
        return;
17642
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
17643
0
    {
17644
0
        dst_window->Pos = src_window->Pos;
17645
0
        dst_window->Size = src_window->Size;
17646
0
        dst_window->SizeFull = src_window->SizeFull;
17647
0
        dst_window->Collapsed = src_window->Collapsed;
17648
0
    }
17649
0
    else if (ImGuiWindowSettings* dst_settings = FindOrCreateWindowSettings(dst_name))
17650
0
    {
17651
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
17652
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
17653
0
        {
17654
0
            dst_settings->ViewportPos = window_pos_2ih;
17655
0
            dst_settings->ViewportId = src_window->ViewportId;
17656
0
            dst_settings->Pos = ImVec2ih(0, 0);
17657
0
        }
17658
0
        else
17659
0
        {
17660
0
            dst_settings->Pos = window_pos_2ih;
17661
0
        }
17662
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
17663
0
        dst_settings->Collapsed = src_window->Collapsed;
17664
0
    }
17665
0
}
17666
17667
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
17668
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
17669
0
{
17670
0
    ImGuiContext& g = *GImGui;
17671
0
    IM_ASSERT(src_dockspace_id != 0);
17672
0
    IM_ASSERT(dst_dockspace_id != 0);
17673
0
    IM_ASSERT(in_window_remap_pairs != NULL);
17674
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
17675
17676
    // Duplicate entire dock
17677
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
17678
    // whereas we could attempt to at least keep them together in a new, same floating node.
17679
0
    ImVector<ImGuiID> node_remap_pairs;
17680
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
17681
17682
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
17683
    // (The windows associated to src_dockspace_id are staying in place)
17684
0
    ImVector<ImGuiID> src_windows;
17685
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
17686
0
    {
17687
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
17688
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
17689
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
17690
0
        src_windows.push_back(src_window_id);
17691
17692
        // Search in the remapping tables
17693
0
        ImGuiID src_dock_id = 0;
17694
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
17695
0
            src_dock_id = src_window->DockId;
17696
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettings(src_window_id))
17697
0
            src_dock_id = src_window_settings->DockId;
17698
0
        ImGuiID dst_dock_id = 0;
17699
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
17700
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
17701
0
            {
17702
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
17703
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
17704
0
                break;
17705
0
            }
17706
17707
0
        if (dst_dock_id != 0)
17708
0
        {
17709
            // Docked windows gets redocked into the new node hierarchy.
17710
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
17711
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
17712
0
        }
17713
0
        else
17714
0
        {
17715
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
17716
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
17717
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
17718
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
17719
0
        }
17720
0
    }
17721
17722
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
17723
    // Find those windows and move to them to the cloned dock node. This may be optional?
17724
    // Dock those are a second step as undocking would invalidate source dock nodes.
17725
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
17726
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
17727
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
17728
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
17729
0
        {
17730
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
17731
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
17732
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17733
0
            {
17734
0
                ImGuiWindow* window = node->Windows[window_n];
17735
0
                if (src_windows.contains(window->ID))
17736
0
                    continue;
17737
17738
                // Docked windows gets redocked into the new node hierarchy.
17739
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
17740
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
17741
0
            }
17742
0
        }
17743
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
17744
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
17745
0
}
17746
17747
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
17748
void ImGui::DockBuilderFinish(ImGuiID root_id)
17749
0
{
17750
0
    ImGuiContext* ctx = GImGui;
17751
    //DockContextRebuild(ctx);
17752
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
17753
0
}
17754
17755
//-----------------------------------------------------------------------------
17756
// Docking: Begin/End Support Functions (called from Begin/End)
17757
//-----------------------------------------------------------------------------
17758
// - GetWindowAlwaysWantOwnTabBar()
17759
// - DockContextBindNodeToWindow()
17760
// - BeginDocked()
17761
// - BeginDockableDragDropSource()
17762
// - BeginDockableDragDropTarget()
17763
//-----------------------------------------------------------------------------
17764
17765
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
17766
180k
{
17767
180k
    ImGuiContext& g = *GImGui;
17768
180k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
17769
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
17770
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
17771
0
                return true;
17772
180k
    return false;
17773
180k
}
17774
17775
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
17776
0
{
17777
0
    ImGuiContext& g = *ctx;
17778
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
17779
0
    IM_ASSERT(window->DockNode == NULL);
17780
17781
    // We should not be docking into a split node (SetWindowDock should avoid this)
17782
0
    if (node && node->IsSplitNode())
17783
0
    {
17784
0
        DockContextProcessUndockWindow(ctx, window);
17785
0
        return NULL;
17786
0
    }
17787
17788
    // Create node
17789
0
    if (node == NULL)
17790
0
    {
17791
0
        node = DockContextAddNode(ctx, window->DockId);
17792
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
17793
0
        node->LastFrameAlive = g.FrameCount;
17794
0
    }
17795
17796
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
17797
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
17798
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
17799
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
17800
0
    if (!node->IsVisible)
17801
0
    {
17802
0
        ImGuiDockNode* ancestor_node = node;
17803
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
17804
0
            ancestor_node = ancestor_node->ParentNode;
17805
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
17806
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
17807
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
17808
0
    }
17809
17810
    // Add window to node
17811
0
    bool node_was_visible = node->IsVisible;
17812
0
    DockNodeAddWindow(node, window, true);
17813
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
17814
0
    IM_ASSERT(node == window->DockNode);
17815
0
    return node;
17816
0
}
17817
17818
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
17819
0
{
17820
0
    ImGuiContext* ctx = GImGui;
17821
0
    ImGuiContext& g = *ctx;
17822
17823
    // Clear fields ahead so most early-out paths don't have to do it
17824
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
17825
17826
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
17827
0
    if (auto_dock_node)
17828
0
    {
17829
0
        if (window->DockId == 0)
17830
0
        {
17831
0
            IM_ASSERT(window->DockNode == NULL);
17832
0
            window->DockId = DockContextGenNodeID(ctx);
17833
0
        }
17834
0
    }
17835
0
    else
17836
0
    {
17837
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
17838
0
        bool want_undock = false;
17839
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
17840
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
17841
0
        if (want_undock)
17842
0
        {
17843
0
            DockContextProcessUndockWindow(ctx, window);
17844
0
            return;
17845
0
        }
17846
0
    }
17847
17848
    // Bind to our dock node
17849
0
    ImGuiDockNode* node = window->DockNode;
17850
0
    if (node != NULL)
17851
0
        IM_ASSERT(window->DockId == node->ID);
17852
0
    if (window->DockId != 0 && node == NULL)
17853
0
    {
17854
0
        node = DockContextBindNodeToWindow(ctx, window);
17855
0
        if (node == NULL)
17856
0
            return;
17857
0
    }
17858
17859
#if 0
17860
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
17861
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
17862
    {
17863
        DockContextProcessUndockWindow(ctx, window);
17864
        return;
17865
    }
17866
#endif
17867
17868
    // Undock if our dockspace node disappeared
17869
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
17870
0
    if (node->LastFrameAlive < g.FrameCount)
17871
0
    {
17872
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
17873
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17874
0
        if (root_node->LastFrameAlive < g.FrameCount)
17875
0
            DockContextProcessUndockWindow(ctx, window);
17876
0
        else
17877
0
            window->DockIsActive = true;
17878
0
        return;
17879
0
    }
17880
17881
    // Store style overrides
17882
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17883
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
17884
17885
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
17886
    // and never create neither a host window neither a tab bar.
17887
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
17888
0
    if (node->HostWindow == NULL)
17889
0
    {
17890
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
17891
0
            window->DockIsActive = true;
17892
0
        if (node->Windows.Size > 1)
17893
0
            DockNodeHideWindowDuringHostWindowCreation(window);
17894
0
        return;
17895
0
    }
17896
17897
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
17898
0
    IM_ASSERT(node->HostWindow);
17899
0
    IM_ASSERT(node->IsLeafNode());
17900
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
17901
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
17902
17903
    // Undock if we are submitted earlier than the host window
17904
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
17905
0
    {
17906
0
        DockContextProcessUndockWindow(ctx, window);
17907
0
        return;
17908
0
    }
17909
17910
    // Position/Size window
17911
0
    SetNextWindowPos(node->Pos);
17912
0
    SetNextWindowSize(node->Size);
17913
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
17914
0
    window->DockIsActive = true;
17915
0
    window->DockNodeIsVisible = true;
17916
0
    window->DockTabIsVisible = false;
17917
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17918
0
        return;
17919
17920
    // When the window is selected we mark it as visible.
17921
0
    if (node->VisibleWindow == window)
17922
0
        window->DockTabIsVisible = true;
17923
17924
    // Update window flag
17925
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
17926
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
17927
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
17928
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
17929
0
    else
17930
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
17931
17932
    // Save new dock order only if the window has been visible once already
17933
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
17934
0
    if (node->TabBar && window->WasActive)
17935
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
17936
17937
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
17938
0
        *p_open = false;
17939
17940
    // Update ChildId to allow returning from Child to Parent with Escape
17941
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
17942
0
    window->ChildId = parent_window->GetID(window->Name);
17943
0
}
17944
17945
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
17946
59
{
17947
59
    ImGuiContext& g = *GImGui;
17948
59
    IM_ASSERT(g.ActiveId == window->MoveId);
17949
59
    IM_ASSERT(g.MovingWindow == window);
17950
59
    IM_ASSERT(g.CurrentWindow == window);
17951
17952
59
    g.LastItemData.ID = window->MoveId;
17953
59
    window = window->RootWindowDockTree;
17954
59
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
17955
59
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
17956
59
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
17957
40
    {
17958
40
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
17959
40
        EndDragDropSource();
17960
17961
        // Store style overrides
17962
280
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17963
240
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
17964
40
    }
17965
59
}
17966
17967
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
17968
60
{
17969
60
    ImGuiContext* ctx = GImGui;
17970
60
    ImGuiContext& g = *ctx;
17971
17972
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
17973
60
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
17974
60
    if (!g.DragDropActive)
17975
0
        return;
17976
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
17977
60
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
17978
60
        return;
17979
17980
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
17981
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
17982
0
    const ImGuiPayload* payload = &g.DragDropPayload;
17983
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
17984
0
    {
17985
0
        EndDragDropTarget();
17986
0
        return;
17987
0
    }
17988
17989
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
17990
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
17991
0
    {
17992
        // Select target node
17993
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
17994
0
        bool dock_into_floating_window = false;
17995
0
        ImGuiDockNode* node = NULL;
17996
0
        if (window->DockNodeAsHost)
17997
0
        {
17998
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
17999
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18000
18001
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18002
            // In this case we need to fallback into any leaf mode, possibly the central node.
18003
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18004
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18005
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18006
0
        }
18007
0
        else
18008
0
        {
18009
0
            if (window->DockNode)
18010
0
                node = window->DockNode;
18011
0
            else
18012
0
                dock_into_floating_window = true; // Dock into a regular window
18013
0
        }
18014
18015
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18016
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18017
18018
        // Preview docking request and find out split direction/ratio
18019
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18020
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18021
0
        if (do_preview && (node != NULL || dock_into_floating_window))
18022
0
        {
18023
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18024
0
            ImGuiDockPreviewData split_inner;
18025
0
            ImGuiDockPreviewData split_outer;
18026
0
            ImGuiDockPreviewData* split_data = &split_inner;
18027
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18028
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18029
0
                {
18030
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18031
0
                    if (split_outer.IsSplitDirExplicit)
18032
0
                        split_data = &split_outer;
18033
0
                }
18034
0
            if (!node || node->IsLeafNode())
18035
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18036
0
            if (split_data == &split_outer)
18037
0
                split_inner.IsDropAllowed = false;
18038
18039
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18040
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18041
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18042
18043
            // Queue docking request
18044
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18045
0
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18046
0
        }
18047
0
    }
18048
0
    EndDragDropTarget();
18049
0
}
18050
18051
//-----------------------------------------------------------------------------
18052
// Docking: Settings
18053
//-----------------------------------------------------------------------------
18054
// - DockSettingsRenameNodeReferences()
18055
// - DockSettingsRemoveNodeReferences()
18056
// - DockSettingsFindNodeSettings()
18057
// - DockSettingsHandler_ApplyAll()
18058
// - DockSettingsHandler_ReadOpen()
18059
// - DockSettingsHandler_ReadLine()
18060
// - DockSettingsHandler_DockNodeToSettings()
18061
// - DockSettingsHandler_WriteAll()
18062
//-----------------------------------------------------------------------------
18063
18064
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18065
0
{
18066
0
    ImGuiContext& g = *GImGui;
18067
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18068
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18069
0
    {
18070
0
        ImGuiWindow* window = g.Windows[window_n];
18071
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18072
0
            window->DockId = new_node_id;
18073
0
    }
18074
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18075
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18076
0
        if (settings->DockId == old_node_id)
18077
0
            settings->DockId = new_node_id;
18078
0
}
18079
18080
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18081
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18082
0
{
18083
0
    ImGuiContext& g = *GImGui;
18084
0
    int found = 0;
18085
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18086
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18087
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18088
0
            if (settings->DockId == node_ids[node_n])
18089
0
            {
18090
0
                settings->DockId = 0;
18091
0
                settings->DockOrder = -1;
18092
0
                if (++found < node_ids_count)
18093
0
                    break;
18094
0
                return;
18095
0
            }
18096
0
}
18097
18098
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18099
0
{
18100
    // FIXME-OPT
18101
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18102
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18103
0
        if (dc->NodesSettings[n].ID == id)
18104
0
            return &dc->NodesSettings[n];
18105
0
    return NULL;
18106
0
}
18107
18108
// Clear settings data
18109
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18110
0
{
18111
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18112
0
    dc->NodesSettings.clear();
18113
0
    DockContextClearNodes(ctx, 0, true);
18114
0
}
18115
18116
// Recreate nodes based on settings data
18117
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18118
0
{
18119
    // Prune settings at boot time only
18120
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18121
0
    if (ctx->Windows.Size == 0)
18122
0
        DockContextPruneUnusedSettingsNodes(ctx);
18123
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18124
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18125
0
}
18126
18127
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18128
0
{
18129
0
    if (strcmp(name, "Data") != 0)
18130
0
        return NULL;
18131
0
    return (void*)1;
18132
0
}
18133
18134
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18135
0
{
18136
0
    char c = 0;
18137
0
    int x = 0, y = 0;
18138
0
    int r = 0;
18139
18140
    // Parsing, e.g.
18141
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18142
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18143
    // Important: this code expect currently fields in a fixed order.
18144
0
    ImGuiDockNodeSettings node;
18145
0
    line = ImStrSkipBlank(line);
18146
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18147
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18148
0
    else return;
18149
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
18150
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
18151
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
18152
0
    if (node.ParentNodeId == 0)
18153
0
    {
18154
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
18155
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
18156
0
    }
18157
0
    else
18158
0
    {
18159
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
18160
0
    }
18161
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
18162
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
18163
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
18164
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
18165
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
18166
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
18167
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
18168
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
18169
0
    if (node.ParentNodeId != 0)
18170
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
18171
0
            node.Depth = parent_settings->Depth + 1;
18172
0
    ctx->DockContext.NodesSettings.push_back(node);
18173
0
}
18174
18175
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
18176
0
{
18177
0
    ImGuiDockNodeSettings node_settings;
18178
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
18179
0
    node_settings.ID = node->ID;
18180
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
18181
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
18182
0
    node_settings.SelectedTabId = node->SelectedTabId;
18183
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
18184
0
    node_settings.Depth = (char)depth;
18185
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
18186
0
    node_settings.Pos = ImVec2ih(node->Pos);
18187
0
    node_settings.Size = ImVec2ih(node->Size);
18188
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
18189
0
    dc->NodesSettings.push_back(node_settings);
18190
0
    if (node->ChildNodes[0])
18191
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
18192
0
    if (node->ChildNodes[1])
18193
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
18194
0
}
18195
18196
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
18197
0
{
18198
0
    ImGuiContext& g = *ctx;
18199
0
    ImGuiDockContext* dc = &ctx->DockContext;
18200
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18201
0
        return;
18202
18203
    // Gather settings data
18204
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
18205
0
    dc->NodesSettings.resize(0);
18206
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
18207
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18208
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18209
0
            if (node->IsRootNode())
18210
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
18211
18212
0
    int max_depth = 0;
18213
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18214
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
18215
18216
    // Write to text buffer
18217
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
18218
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18219
0
    {
18220
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
18221
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
18222
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
18223
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
18224
0
        if (node_settings->ParentNodeId)
18225
0
        {
18226
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
18227
0
        }
18228
0
        else
18229
0
        {
18230
0
            if (node_settings->ParentWindowId)
18231
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
18232
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
18233
0
        }
18234
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
18235
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
18236
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
18237
0
            buf->appendf(" NoResize=1");
18238
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
18239
0
            buf->appendf(" CentralNode=1");
18240
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
18241
0
            buf->appendf(" NoTabBar=1");
18242
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
18243
0
            buf->appendf(" HiddenTabBar=1");
18244
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
18245
0
            buf->appendf(" NoWindowMenuButton=1");
18246
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
18247
0
            buf->appendf(" NoCloseButton=1");
18248
0
        if (node_settings->SelectedTabId)
18249
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
18250
18251
#if IMGUI_DEBUG_INI_SETTINGS
18252
        // [DEBUG] Include comments in the .ini file to ease debugging
18253
        if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
18254
        {
18255
            buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
18256
            if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
18257
                buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
18258
            // Iterate settings so we can give info about windows that didn't exist during the session.
18259
            int contains_window = 0;
18260
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18261
                if (settings->DockId == node_settings->ID)
18262
                {
18263
                    if (contains_window++ == 0)
18264
                        buf->appendf(" ; contains ");
18265
                    buf->appendf("'%s' ", settings->GetName());
18266
                }
18267
        }
18268
#endif
18269
0
        buf->appendf("\n");
18270
0
    }
18271
0
    buf->appendf("\n");
18272
0
}
18273
18274
18275
//-----------------------------------------------------------------------------
18276
// [SECTION] PLATFORM DEPENDENT HELPERS
18277
//-----------------------------------------------------------------------------
18278
18279
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
18280
18281
#ifdef _MSC_VER
18282
#pragma comment(lib, "user32")
18283
#pragma comment(lib, "kernel32")
18284
#endif
18285
18286
// Win32 clipboard implementation
18287
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
18288
static const char* GetClipboardTextFn_DefaultImpl(void*)
18289
{
18290
    ImGuiContext& g = *GImGui;
18291
    g.ClipboardHandlerData.clear();
18292
    if (!::OpenClipboard(NULL))
18293
        return NULL;
18294
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
18295
    if (wbuf_handle == NULL)
18296
    {
18297
        ::CloseClipboard();
18298
        return NULL;
18299
    }
18300
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
18301
    {
18302
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
18303
        g.ClipboardHandlerData.resize(buf_len);
18304
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
18305
    }
18306
    ::GlobalUnlock(wbuf_handle);
18307
    ::CloseClipboard();
18308
    return g.ClipboardHandlerData.Data;
18309
}
18310
18311
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18312
{
18313
    if (!::OpenClipboard(NULL))
18314
        return;
18315
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
18316
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
18317
    if (wbuf_handle == NULL)
18318
    {
18319
        ::CloseClipboard();
18320
        return;
18321
    }
18322
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
18323
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
18324
    ::GlobalUnlock(wbuf_handle);
18325
    ::EmptyClipboard();
18326
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
18327
        ::GlobalFree(wbuf_handle);
18328
    ::CloseClipboard();
18329
}
18330
18331
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
18332
18333
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
18334
static PasteboardRef main_clipboard = 0;
18335
18336
// OSX clipboard implementation
18337
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
18338
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18339
{
18340
    if (!main_clipboard)
18341
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18342
    PasteboardClear(main_clipboard);
18343
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
18344
    if (cf_data)
18345
    {
18346
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
18347
        CFRelease(cf_data);
18348
    }
18349
}
18350
18351
static const char* GetClipboardTextFn_DefaultImpl(void*)
18352
{
18353
    if (!main_clipboard)
18354
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18355
    PasteboardSynchronize(main_clipboard);
18356
18357
    ItemCount item_count = 0;
18358
    PasteboardGetItemCount(main_clipboard, &item_count);
18359
    for (ItemCount i = 0; i < item_count; i++)
18360
    {
18361
        PasteboardItemID item_id = 0;
18362
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
18363
        CFArrayRef flavor_type_array = 0;
18364
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
18365
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
18366
        {
18367
            CFDataRef cf_data;
18368
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
18369
            {
18370
                ImGuiContext& g = *GImGui;
18371
                g.ClipboardHandlerData.clear();
18372
                int length = (int)CFDataGetLength(cf_data);
18373
                g.ClipboardHandlerData.resize(length + 1);
18374
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
18375
                g.ClipboardHandlerData[length] = 0;
18376
                CFRelease(cf_data);
18377
                return g.ClipboardHandlerData.Data;
18378
            }
18379
        }
18380
    }
18381
    return NULL;
18382
}
18383
18384
#else
18385
18386
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
18387
static const char* GetClipboardTextFn_DefaultImpl(void*)
18388
0
{
18389
0
    ImGuiContext& g = *GImGui;
18390
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
18391
0
}
18392
18393
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18394
0
{
18395
0
    ImGuiContext& g = *GImGui;
18396
0
    g.ClipboardHandlerData.clear();
18397
0
    const char* text_end = text + strlen(text);
18398
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
18399
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
18400
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
18401
0
}
18402
18403
#endif
18404
18405
// Win32 API IME support (for Asian languages, etc.)
18406
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
18407
18408
#include <imm.h>
18409
#ifdef _MSC_VER
18410
#pragma comment(lib, "imm32")
18411
#endif
18412
18413
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
18414
{
18415
    // Notify OS Input Method Editor of text input position
18416
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
18417
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
18418
    if (hwnd == 0)
18419
        hwnd = (HWND)ImGui::GetIO().ImeWindowHandle;
18420
#endif
18421
    if (hwnd == 0)
18422
        return;
18423
18424
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
18425
    if (HIMC himc = ::ImmGetContext(hwnd))
18426
    {
18427
        COMPOSITIONFORM composition_form = {};
18428
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18429
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18430
        composition_form.dwStyle = CFS_FORCE_POSITION;
18431
        ::ImmSetCompositionWindow(himc, &composition_form);
18432
        CANDIDATEFORM candidate_form = {};
18433
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
18434
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18435
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18436
        ::ImmSetCandidateWindow(himc, &candidate_form);
18437
        ::ImmReleaseContext(hwnd, himc);
18438
    }
18439
}
18440
18441
#else
18442
18443
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
18444
18445
#endif
18446
18447
//-----------------------------------------------------------------------------
18448
// [SECTION] METRICS/DEBUGGER WINDOW
18449
//-----------------------------------------------------------------------------
18450
// - RenderViewportThumbnail() [Internal]
18451
// - RenderViewportsThumbnails() [Internal]
18452
// - DebugTextEncoding()
18453
// - MetricsHelpMarker() [Internal]
18454
// - ShowFontAtlas() [Internal]
18455
// - ShowMetricsWindow()
18456
// - DebugNodeColumns() [Internal]
18457
// - DebugNodeDockNode() [Internal]
18458
// - DebugNodeDrawList() [Internal]
18459
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
18460
// - DebugNodeFont() [Internal]
18461
// - DebugNodeFontGlyph() [Internal]
18462
// - DebugNodeStorage() [Internal]
18463
// - DebugNodeTabBar() [Internal]
18464
// - DebugNodeViewport() [Internal]
18465
// - DebugNodeWindow() [Internal]
18466
// - DebugNodeWindowSettings() [Internal]
18467
// - DebugNodeWindowsList() [Internal]
18468
// - DebugNodeWindowsListByBeginStackParent() [Internal]
18469
//-----------------------------------------------------------------------------
18470
18471
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
18472
18473
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
18474
0
{
18475
0
    ImGuiContext& g = *GImGui;
18476
0
    ImGuiWindow* window = g.CurrentWindow;
18477
18478
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
18479
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
18480
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f;
18481
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
18482
0
    for (int i = 0; i != g.Windows.Size; i++)
18483
0
    {
18484
0
        ImGuiWindow* thumb_window = g.Windows[i];
18485
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
18486
0
            continue;
18487
0
        if (thumb_window->Viewport != viewport)
18488
0
            continue;
18489
18490
0
        ImRect thumb_r = thumb_window->Rect();
18491
0
        ImRect title_r = thumb_window->TitleBarRect();
18492
0
        thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off +  thumb_r.Max * scale));
18493
0
        title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
18494
0
        thumb_r.ClipWithFull(bb);
18495
0
        title_r.ClipWithFull(bb);
18496
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
18497
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
18498
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
18499
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18500
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
18501
0
    }
18502
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18503
0
}
18504
18505
static void RenderViewportsThumbnails()
18506
0
{
18507
0
    ImGuiContext& g = *GImGui;
18508
0
    ImGuiWindow* window = g.CurrentWindow;
18509
18510
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
18511
0
    float SCALE = 1.0f / 8.0f;
18512
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
18513
0
    for (int n = 0; n < g.Viewports.Size; n++)
18514
0
        bb_full.Add(g.Viewports[n]->GetMainRect());
18515
0
    ImVec2 p = window->DC.CursorPos;
18516
0
    ImVec2 off = p - bb_full.Min * SCALE;
18517
0
    for (int n = 0; n < g.Viewports.Size; n++)
18518
0
    {
18519
0
        ImGuiViewportP* viewport = g.Viewports[n];
18520
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
18521
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
18522
0
    }
18523
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
18524
0
}
18525
18526
static int IMGUI_CDECL ViewportComparerByFrontMostStampCount(const void* lhs, const void* rhs)
18527
0
{
18528
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
18529
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
18530
0
    return b->LastFrontMostStampCount - a->LastFrontMostStampCount;
18531
0
}
18532
18533
// Draw an arbitrary US keyboard layout to visualize translated keys
18534
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
18535
0
{
18536
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
18537
0
    const float  key_rounding = 3.0f;
18538
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
18539
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
18540
0
    const float  key_face_rounding = 2.0f;
18541
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
18542
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
18543
0
    const float  key_row_offset = 9.0f;
18544
18545
0
    ImVec2 board_min = GetCursorScreenPos();
18546
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
18547
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
18548
18549
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
18550
0
    const KeyLayoutData keys_to_display[] =
18551
0
    {
18552
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
18553
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
18554
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
18555
0
    };
18556
18557
    // Elements rendered manually via ImDrawList API are not clipped automatically.
18558
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
18559
0
    Dummy(board_max - board_min);
18560
0
    if (!IsItemVisible())
18561
0
        return;
18562
0
    draw_list->PushClipRect(board_min, board_max, true);
18563
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
18564
0
    {
18565
0
        const KeyLayoutData* key_data = &keys_to_display[n];
18566
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
18567
0
        ImVec2 key_max = key_min + key_size;
18568
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
18569
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
18570
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
18571
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
18572
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
18573
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
18574
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
18575
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
18576
0
        if (ImGui::IsKeyDown(key_data->Key))
18577
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
18578
0
    }
18579
0
    draw_list->PopClipRect();
18580
0
}
18581
18582
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
18583
void ImGui::DebugTextEncoding(const char* str)
18584
0
{
18585
0
    Text("Text: \"%s\"", str);
18586
0
    if (!BeginTable("list", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit))
18587
0
        return;
18588
0
    TableSetupColumn("Offset");
18589
0
    TableSetupColumn("UTF-8");
18590
0
    TableSetupColumn("Glyph");
18591
0
    TableSetupColumn("Codepoint");
18592
0
    TableHeadersRow();
18593
0
    for (const char* p = str; *p != 0; )
18594
0
    {
18595
0
        unsigned int c;
18596
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
18597
0
        TableNextColumn();
18598
0
        Text("%d", (int)(p - str));
18599
0
        TableNextColumn();
18600
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
18601
0
        {
18602
0
            if (byte_index > 0)
18603
0
                SameLine();
18604
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
18605
0
        }
18606
0
        TableNextColumn();
18607
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
18608
0
            TextUnformatted(p, p + c_utf8_len);
18609
0
        else
18610
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
18611
0
        TableNextColumn();
18612
0
        Text("U+%04X", (int)c);
18613
0
        p += c_utf8_len;
18614
0
    }
18615
0
    EndTable();
18616
0
}
18617
18618
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
18619
static void MetricsHelpMarker(const char* desc)
18620
0
{
18621
0
    ImGui::TextDisabled("(?)");
18622
0
    if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort))
18623
0
    {
18624
0
        ImGui::BeginTooltip();
18625
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
18626
0
        ImGui::TextUnformatted(desc);
18627
0
        ImGui::PopTextWrapPos();
18628
0
        ImGui::EndTooltip();
18629
0
    }
18630
0
}
18631
18632
// [DEBUG] List fonts in a font atlas and display its texture
18633
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
18634
0
{
18635
0
    for (int i = 0; i < atlas->Fonts.Size; i++)
18636
0
    {
18637
0
        ImFont* font = atlas->Fonts[i];
18638
0
        PushID(font);
18639
0
        DebugNodeFont(font);
18640
0
        PopID();
18641
0
    }
18642
0
    if (TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
18643
0
    {
18644
0
        ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
18645
0
        ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f);
18646
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
18647
0
        TreePop();
18648
0
    }
18649
0
}
18650
18651
void ImGui::ShowMetricsWindow(bool* p_open)
18652
0
{
18653
0
    ImGuiContext& g = *GImGui;
18654
0
    ImGuiIO& io = g.IO;
18655
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
18656
0
    if (cfg->ShowDebugLog)
18657
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
18658
0
    if (cfg->ShowStackTool)
18659
0
        ShowStackToolWindow(&cfg->ShowStackTool);
18660
18661
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
18662
0
    {
18663
0
        End();
18664
0
        return;
18665
0
    }
18666
18667
    // Basic info
18668
0
    Text("Dear ImGui %s", GetVersion());
18669
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
18670
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
18671
0
    Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
18672
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
18673
18674
0
    Separator();
18675
18676
    // Debugging enums
18677
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
18678
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
18679
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
18680
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
18681
0
    if (cfg->ShowWindowsRectsType < 0)
18682
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
18683
0
    if (cfg->ShowTablesRectsType < 0)
18684
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
18685
18686
0
    struct Funcs
18687
0
    {
18688
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
18689
0
        {
18690
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
18691
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
18692
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
18693
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
18694
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
18695
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
18696
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
18697
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
18698
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
18699
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
18700
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); } // Note: y1/y2 not always accurate
18701
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
18702
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
18703
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
18704
0
            IM_ASSERT(0);
18705
0
            return ImRect();
18706
0
        }
18707
18708
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
18709
0
        {
18710
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
18711
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
18712
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
18713
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
18714
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
18715
0
            else if (rect_type == WRT_Content)       { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
18716
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
18717
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
18718
0
            IM_ASSERT(0);
18719
0
            return ImRect();
18720
0
        }
18721
0
    };
18722
18723
    // Tools
18724
0
    if (TreeNode("Tools"))
18725
0
    {
18726
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
18727
0
        SameLine();
18728
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
18729
0
        if (show_encoding_viewer)
18730
0
        {
18731
0
            static char buf[100] = "";
18732
0
            SetNextItemWidth(-FLT_MIN);
18733
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
18734
0
            if (buf[0] != 0)
18735
0
                DebugTextEncoding(buf);
18736
0
            TreePop();
18737
0
        }
18738
18739
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
18740
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
18741
0
            DebugStartItemPicker();
18742
0
        SameLine();
18743
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
18744
18745
        // Stack Tool is your best friend!
18746
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
18747
0
        SameLine();
18748
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
18749
18750
        // Stack Tool is your best friend!
18751
0
        Checkbox("Show Stack Tool", &cfg->ShowStackTool);
18752
0
        SameLine();
18753
0
        MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
18754
18755
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
18756
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
18757
0
        SameLine();
18758
0
        SetNextItemWidth(GetFontSize() * 12);
18759
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
18760
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
18761
0
        {
18762
0
            BulletText("'%s':", g.NavWindow->Name);
18763
0
            Indent();
18764
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
18765
0
            {
18766
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
18767
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
18768
0
            }
18769
0
            Unindent();
18770
0
        }
18771
18772
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
18773
0
        SameLine();
18774
0
        SetNextItemWidth(GetFontSize() * 12);
18775
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
18776
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
18777
0
        {
18778
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
18779
0
            {
18780
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
18781
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
18782
0
                    continue;
18783
18784
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
18785
0
                if (IsItemHovered())
18786
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18787
0
                Indent();
18788
0
                char buf[128];
18789
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
18790
0
                {
18791
0
                    if (rect_n >= TRT_ColumnsRect)
18792
0
                    {
18793
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
18794
0
                            continue;
18795
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
18796
0
                        {
18797
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
18798
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
18799
0
                            Selectable(buf);
18800
0
                            if (IsItemHovered())
18801
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18802
0
                        }
18803
0
                    }
18804
0
                    else
18805
0
                    {
18806
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
18807
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
18808
0
                        Selectable(buf);
18809
0
                        if (IsItemHovered())
18810
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18811
0
                    }
18812
0
                }
18813
0
                Unindent();
18814
0
            }
18815
0
        }
18816
18817
0
        TreePop();
18818
0
    }
18819
18820
    // Windows
18821
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
18822
0
    {
18823
        //SetNextItemOpen(true, ImGuiCond_Once);
18824
0
        DebugNodeWindowsList(&g.Windows, "By display order");
18825
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
18826
0
        if (TreeNode("By submission order (begin stack)"))
18827
0
        {
18828
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
18829
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
18830
0
            temp_buffer.resize(0);
18831
0
            for (int i = 0; i < g.Windows.Size; i++)
18832
0
                if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)
18833
0
                    temp_buffer.push_back(g.Windows[i]);
18834
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
18835
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
18836
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
18837
0
            TreePop();
18838
0
        }
18839
18840
0
        TreePop();
18841
0
    }
18842
18843
    // DrawLists
18844
0
    int drawlist_count = 0;
18845
0
    for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
18846
0
        drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
18847
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
18848
0
    {
18849
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
18850
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
18851
0
        for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
18852
0
        {
18853
0
            ImGuiViewportP* viewport = g.Viewports[viewport_i];
18854
0
            bool viewport_has_drawlist = false;
18855
0
            for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
18856
0
                for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
18857
0
                {
18858
0
                    if (!viewport_has_drawlist)
18859
0
                        Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
18860
0
                    viewport_has_drawlist = true;
18861
0
                    DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
18862
0
                }
18863
0
        }
18864
0
        TreePop();
18865
0
    }
18866
18867
    // Viewports
18868
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
18869
0
    {
18870
0
        Indent(GetTreeNodeToLabelSpacing());
18871
0
        RenderViewportsThumbnails();
18872
0
        Unindent(GetTreeNodeToLabelSpacing());
18873
18874
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
18875
0
        SameLine();
18876
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
18877
0
        if (open)
18878
0
        {
18879
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
18880
0
            {
18881
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
18882
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
18883
0
                    i, mon.DpiScale * 100.0f,
18884
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
18885
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
18886
0
            }
18887
0
            TreePop();
18888
0
        }
18889
18890
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
18891
0
        if (TreeNode("Inferred Z order (front-to-back)"))
18892
0
        {
18893
0
            static ImVector<ImGuiViewportP*> viewports;
18894
0
            viewports.resize(g.Viewports.Size);
18895
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
18896
0
            if (viewports.Size > 1)
18897
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByFrontMostStampCount);
18898
0
            for (int i = 0; i < viewports.Size; i++)
18899
0
                BulletText("Viewport #%d, ID: 0x%08X, FrontMostStampCount = %08d, Window: \"%s\"", viewports[i]->Idx, viewports[i]->ID, viewports[i]->LastFrontMostStampCount, viewports[i]->Window ? viewports[i]->Window->Name : "N/A");
18900
0
            TreePop();
18901
0
        }
18902
18903
0
        for (int i = 0; i < g.Viewports.Size; i++)
18904
0
            DebugNodeViewport(g.Viewports[i]);
18905
0
        TreePop();
18906
0
    }
18907
18908
    // Details for Popups
18909
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
18910
0
    {
18911
0
        for (int i = 0; i < g.OpenPopupStack.Size; i++)
18912
0
        {
18913
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
18914
0
            const ImGuiPopupData* popup_data = &g.OpenPopupStack[i];
18915
0
            ImGuiWindow* window = popup_data->Window;
18916
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
18917
0
                popup_data->PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
18918
0
                popup_data->BackupNavWindow ? popup_data->BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
18919
0
        }
18920
0
        TreePop();
18921
0
    }
18922
18923
    // Details for TabBars
18924
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
18925
0
    {
18926
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
18927
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
18928
0
            {
18929
0
                PushID(tab_bar);
18930
0
                DebugNodeTabBar(tab_bar, "TabBar");
18931
0
                PopID();
18932
0
            }
18933
0
        TreePop();
18934
0
    }
18935
18936
    // Details for Tables
18937
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
18938
0
    {
18939
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
18940
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
18941
0
                DebugNodeTable(table);
18942
0
        TreePop();
18943
0
    }
18944
18945
    // Details for Fonts
18946
0
    ImFontAtlas* atlas = g.IO.Fonts;
18947
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
18948
0
    {
18949
0
        ShowFontAtlas(atlas);
18950
0
        TreePop();
18951
0
    }
18952
18953
    // Details for InputText
18954
0
    if (TreeNode("InputText"))
18955
0
    {
18956
0
        DebugNodeInputTextState(&g.InputTextState);
18957
0
        TreePop();
18958
0
    }
18959
18960
    // Details for Docking
18961
0
#ifdef IMGUI_HAS_DOCK
18962
0
    if (TreeNode("Docking"))
18963
0
    {
18964
0
        static bool root_nodes_only = true;
18965
0
        ImGuiDockContext* dc = &g.DockContext;
18966
0
        Checkbox("List root nodes", &root_nodes_only);
18967
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
18968
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
18969
0
        SameLine();
18970
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
18971
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
18972
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18973
0
                if (!root_nodes_only || node->IsRootNode())
18974
0
                    DebugNodeDockNode(node, "Node");
18975
0
        TreePop();
18976
0
    }
18977
0
#endif // #ifdef IMGUI_HAS_DOCK
18978
18979
    // Settings
18980
0
    if (TreeNode("Settings"))
18981
0
    {
18982
0
        if (SmallButton("Clear"))
18983
0
            ClearIniSettings();
18984
0
        SameLine();
18985
0
        if (SmallButton("Save to memory"))
18986
0
            SaveIniSettingsToMemory();
18987
0
        SameLine();
18988
0
        if (SmallButton("Save to disk"))
18989
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
18990
0
        SameLine();
18991
0
        if (g.IO.IniFilename)
18992
0
            Text("\"%s\"", g.IO.IniFilename);
18993
0
        else
18994
0
            TextUnformatted("<NULL>");
18995
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
18996
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
18997
0
        {
18998
0
            for (int n = 0; n < g.SettingsHandlers.Size; n++)
18999
0
                BulletText("%s", g.SettingsHandlers[n].TypeName);
19000
0
            TreePop();
19001
0
        }
19002
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19003
0
        {
19004
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19005
0
                DebugNodeWindowSettings(settings);
19006
0
            TreePop();
19007
0
        }
19008
19009
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19010
0
        {
19011
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19012
0
                DebugNodeTableSettings(settings);
19013
0
            TreePop();
19014
0
        }
19015
19016
0
#ifdef IMGUI_HAS_DOCK
19017
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19018
0
        {
19019
0
            ImGuiDockContext* dc = &g.DockContext;
19020
0
            Text("In SettingsWindows:");
19021
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19022
0
                if (settings->DockId != 0)
19023
0
                    BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId);
19024
0
            Text("In SettingsNodes:");
19025
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19026
0
            {
19027
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19028
0
                const char* selected_tab_name = NULL;
19029
0
                if (settings->SelectedTabId)
19030
0
                {
19031
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19032
0
                        selected_tab_name = window->Name;
19033
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedTabId))
19034
0
                        selected_tab_name = window_settings->GetName();
19035
0
                }
19036
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19037
0
            }
19038
0
            TreePop();
19039
0
        }
19040
0
#endif // #ifdef IMGUI_HAS_DOCK
19041
19042
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19043
0
        {
19044
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19045
0
            TreePop();
19046
0
        }
19047
0
        TreePop();
19048
0
    }
19049
19050
0
    if (TreeNode("Inputs"))
19051
0
    {
19052
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19053
0
        {
19054
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19055
            // User code should never have to go through such hoops: old code may use native keycodes, new code may use ImGuiKey codes.
19056
0
            Indent();
19057
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19058
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19059
#else
19060
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19061
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19062
#endif
19063
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19064
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19065
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19066
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19067
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19068
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19069
0
            Unindent();
19070
0
        }
19071
19072
0
        Text("MOUSE STATE");
19073
0
        {
19074
0
            Indent();
19075
0
            if (IsMousePosValid())
19076
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19077
0
            else
19078
0
                Text("Mouse pos: <INVALID>");
19079
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19080
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19081
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19082
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19083
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19084
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19085
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19086
0
            Unindent();
19087
0
        }
19088
19089
0
        Text("MOUSE WHEELING");
19090
0
        {
19091
0
            Indent();
19092
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19093
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19094
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19095
0
            Unindent();
19096
0
        }
19097
19098
0
        Text("KEY OWNERS");
19099
0
        {
19100
0
            Indent();
19101
0
            if (BeginListBox("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19102
0
            {
19103
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19104
0
                {
19105
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
19106
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
19107
0
                        continue;
19108
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
19109
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
19110
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
19111
0
                }
19112
0
                EndListBox();
19113
0
            }
19114
0
            Unindent();
19115
0
        }
19116
0
        Text("SHORTCUT ROUTING");
19117
0
        {
19118
0
            Indent();
19119
0
            if (BeginListBox("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19120
0
            {
19121
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19122
0
                {
19123
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
19124
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
19125
0
                    {
19126
0
                        char key_chord_name[64];
19127
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
19128
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
19129
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
19130
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
19131
0
                        idx = routing_data->NextEntryIndex;
19132
0
                    }
19133
0
                }
19134
0
                EndListBox();
19135
0
            }
19136
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19137
0
            Unindent();
19138
0
        }
19139
0
        TreePop();
19140
0
    }
19141
19142
0
    if (TreeNode("Internal state"))
19143
0
    {
19144
0
        Text("WINDOWING");
19145
0
        Indent();
19146
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
19147
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
19148
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
19149
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
19150
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
19151
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19152
0
        Unindent();
19153
19154
0
        Text("ITEMS");
19155
0
        Indent();
19156
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
19157
0
        DebugLocateItemOnHover(g.ActiveId);
19158
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
19159
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19160
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
19161
0
        Text("HoverDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverDelayId, g.HoverDelayTimer, g.HoverDelayClearTimer);
19162
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
19163
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
19164
0
        Unindent();
19165
19166
0
        Text("NAV,FOCUS");
19167
0
        Indent();
19168
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
19169
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
19170
0
        DebugLocateItemOnHover(g.NavId);
19171
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
19172
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
19173
0
        Text("NavActivateId/DownId/PressedId/InputId: %08X/%08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId, g.NavActivateInputId);
19174
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
19175
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
19176
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
19177
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
19178
0
        Unindent();
19179
19180
0
        TreePop();
19181
0
    }
19182
19183
    // Overlay: Display windows Rectangles and Begin Order
19184
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
19185
0
    {
19186
0
        for (int n = 0; n < g.Windows.Size; n++)
19187
0
        {
19188
0
            ImGuiWindow* window = g.Windows[n];
19189
0
            if (!window->WasActive)
19190
0
                continue;
19191
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
19192
0
            if (cfg->ShowWindowsRects)
19193
0
            {
19194
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
19195
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19196
0
            }
19197
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
19198
0
            {
19199
0
                char buf[32];
19200
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
19201
0
                float font_size = GetFontSize();
19202
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
19203
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
19204
0
            }
19205
0
        }
19206
0
    }
19207
19208
    // Overlay: Display Tables Rectangles
19209
0
    if (cfg->ShowTablesRects)
19210
0
    {
19211
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19212
0
        {
19213
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19214
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
19215
0
                continue;
19216
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
19217
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
19218
0
            {
19219
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19220
0
                {
19221
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
19222
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
19223
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
19224
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
19225
0
                }
19226
0
            }
19227
0
            else
19228
0
            {
19229
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
19230
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19231
0
            }
19232
0
        }
19233
0
    }
19234
19235
0
#ifdef IMGUI_HAS_DOCK
19236
    // Overlay: Display Docking info
19237
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
19238
0
    {
19239
0
        char buf[64] = "";
19240
0
        char* p = buf;
19241
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
19242
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19243
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
19244
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
19245
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
19246
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
19247
0
        int depth = DockNodeGetDepth(node);
19248
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
19249
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
19250
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
19251
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
19252
0
    }
19253
0
#endif // #ifdef IMGUI_HAS_DOCK
19254
19255
0
    End();
19256
0
}
19257
19258
// [DEBUG] Display contents of Columns
19259
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
19260
0
{
19261
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
19262
0
        return;
19263
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
19264
0
    for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
19265
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
19266
0
    TreePop();
19267
0
}
19268
19269
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
19270
0
{
19271
0
    using namespace ImGui;
19272
0
    PushID(label);
19273
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
19274
0
    Text("%s:", label);
19275
0
    if (!enabled)
19276
0
        BeginDisabled();
19277
0
    CheckboxFlags("NoSplit", p_flags, ImGuiDockNodeFlags_NoSplit);
19278
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
19279
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
19280
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
19281
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
19282
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
19283
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
19284
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
19285
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking);
19286
0
    CheckboxFlags("NoDockingSplitMe", p_flags, ImGuiDockNodeFlags_NoDockingSplitMe);
19287
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
19288
0
    CheckboxFlags("NoDockingOverMe", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
19289
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
19290
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
19291
0
    if (!enabled)
19292
0
        EndDisabled();
19293
0
    PopStyleVar();
19294
0
    PopID();
19295
0
}
19296
19297
// [DEBUG] Display contents of ImDockNode
19298
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
19299
0
{
19300
0
    ImGuiContext& g = *GImGui;
19301
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
19302
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
19303
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19304
0
    bool open;
19305
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19306
0
    if (node->Windows.Size > 0)
19307
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19308
0
    else
19309
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19310
0
    if (!is_alive) { PopStyleColor(); }
19311
0
    if (is_active && IsItemHovered())
19312
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
19313
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
19314
0
    if (open)
19315
0
    {
19316
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
19317
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
19318
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
19319
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
19320
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
19321
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
19322
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
19323
0
        BulletText("Misc:%s%s%s%s%s%s%s",
19324
0
            node->IsDockSpace() ? " IsDockSpace" : "",
19325
0
            node->IsCentralNode() ? " IsCentralNode" : "",
19326
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
19327
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
19328
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
19329
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
19330
0
        {
19331
0
            if (BeginTable("flags", 4))
19332
0
            {
19333
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
19334
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
19335
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
19336
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
19337
0
                EndTable();
19338
0
            }
19339
0
            TreePop();
19340
0
        }
19341
0
        if (node->ParentNode)
19342
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
19343
0
        if (node->ChildNodes[0])
19344
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
19345
0
        if (node->ChildNodes[1])
19346
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
19347
0
        if (node->TabBar)
19348
0
            DebugNodeTabBar(node->TabBar, "TabBar");
19349
0
        DebugNodeWindowsList(&node->Windows, "Windows");
19350
19351
0
        TreePop();
19352
0
    }
19353
0
}
19354
19355
// [DEBUG] Display contents of ImDrawList
19356
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
19357
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
19358
0
{
19359
0
    ImGuiContext& g = *GImGui;
19360
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19361
0
    int cmd_count = draw_list->CmdBuffer.Size;
19362
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
19363
0
        cmd_count--;
19364
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
19365
0
    if (draw_list == GetWindowDrawList())
19366
0
    {
19367
0
        SameLine();
19368
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
19369
0
        if (node_open)
19370
0
            TreePop();
19371
0
        return;
19372
0
    }
19373
19374
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
19375
0
    if (window && IsItemHovered() && fg_draw_list)
19376
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19377
0
    if (!node_open)
19378
0
        return;
19379
19380
0
    if (window && !window->WasActive)
19381
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
19382
19383
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
19384
0
    {
19385
0
        if (pcmd->UserCallback)
19386
0
        {
19387
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
19388
0
            continue;
19389
0
        }
19390
19391
0
        char buf[300];
19392
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
19393
0
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
19394
0
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
19395
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
19396
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
19397
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
19398
0
        if (!pcmd_node_open)
19399
0
            continue;
19400
19401
        // Calculate approximate coverage area (touched pixel count)
19402
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
19403
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
19404
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
19405
0
        float total_area = 0.0f;
19406
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
19407
0
        {
19408
0
            ImVec2 triangle[3];
19409
0
            for (int n = 0; n < 3; n++, idx_n++)
19410
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
19411
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
19412
0
        }
19413
19414
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
19415
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
19416
0
        Selectable(buf);
19417
0
        if (IsItemHovered() && fg_draw_list)
19418
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
19419
19420
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
19421
0
        ImGuiListClipper clipper;
19422
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
19423
0
        while (clipper.Step())
19424
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
19425
0
            {
19426
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
19427
0
                ImVec2 triangle[3];
19428
0
                for (int n = 0; n < 3; n++, idx_i++)
19429
0
                {
19430
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
19431
0
                    triangle[n] = v.pos;
19432
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
19433
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
19434
0
                }
19435
19436
0
                Selectable(buf, false);
19437
0
                if (fg_draw_list && IsItemHovered())
19438
0
                {
19439
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
19440
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19441
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
19442
0
                    fg_draw_list->Flags = backup_flags;
19443
0
                }
19444
0
            }
19445
0
        TreePop();
19446
0
    }
19447
0
    TreePop();
19448
0
}
19449
19450
// [DEBUG] Display mesh/aabb of a ImDrawCmd
19451
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
19452
0
{
19453
0
    IM_ASSERT(show_mesh || show_aabb);
19454
19455
    // Draw wire-frame version of all triangles
19456
0
    ImRect clip_rect = draw_cmd->ClipRect;
19457
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19458
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
19459
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19460
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
19461
0
    {
19462
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
19463
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
19464
19465
0
        ImVec2 triangle[3];
19466
0
        for (int n = 0; n < 3; n++, idx_n++)
19467
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
19468
0
        if (show_mesh)
19469
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
19470
0
    }
19471
    // Draw bounding boxes
19472
0
    if (show_aabb)
19473
0
    {
19474
0
        out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
19475
0
        out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
19476
0
    }
19477
0
    out_draw_list->Flags = backup_flags;
19478
0
}
19479
19480
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
19481
void ImGui::DebugNodeFont(ImFont* font)
19482
0
{
19483
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
19484
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
19485
0
    SameLine();
19486
0
    if (SmallButton("Set as default"))
19487
0
        GetIO().FontDefault = font;
19488
0
    if (!opened)
19489
0
        return;
19490
19491
    // Display preview text
19492
0
    PushFont(font);
19493
0
    Text("The quick brown fox jumps over the lazy dog");
19494
0
    PopFont();
19495
19496
    // Display details
19497
0
    SetNextItemWidth(GetFontSize() * 8);
19498
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
19499
0
    SameLine(); MetricsHelpMarker(
19500
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
19501
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
19502
0
        "You may oversample them to get some flexibility with scaling. "
19503
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
19504
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
19505
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
19506
0
    char c_str[5];
19507
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
19508
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
19509
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
19510
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
19511
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
19512
0
        if (font->ConfigData)
19513
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
19514
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
19515
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
19516
19517
    // Display all glyphs of the fonts in separate pages of 256 characters
19518
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
19519
0
    {
19520
0
        ImDrawList* draw_list = GetWindowDrawList();
19521
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
19522
0
        const float cell_size = font->FontSize * 1;
19523
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
19524
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
19525
0
        {
19526
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
19527
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
19528
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
19529
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
19530
0
            {
19531
0
                base += 4096 - 256;
19532
0
                continue;
19533
0
            }
19534
19535
0
            int count = 0;
19536
0
            for (unsigned int n = 0; n < 256; n++)
19537
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
19538
0
                    count++;
19539
0
            if (count <= 0)
19540
0
                continue;
19541
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
19542
0
                continue;
19543
19544
            // Draw a 16x16 grid of glyphs
19545
0
            ImVec2 base_pos = GetCursorScreenPos();
19546
0
            for (unsigned int n = 0; n < 256; n++)
19547
0
            {
19548
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
19549
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
19550
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
19551
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
19552
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
19553
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
19554
0
                if (!glyph)
19555
0
                    continue;
19556
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
19557
0
                if (IsMouseHoveringRect(cell_p1, cell_p2))
19558
0
                {
19559
0
                    BeginTooltip();
19560
0
                    DebugNodeFontGlyph(font, glyph);
19561
0
                    EndTooltip();
19562
0
                }
19563
0
            }
19564
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
19565
0
            TreePop();
19566
0
        }
19567
0
        TreePop();
19568
0
    }
19569
0
    TreePop();
19570
0
}
19571
19572
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
19573
0
{
19574
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
19575
0
    Separator();
19576
0
    Text("Visible: %d", glyph->Visible);
19577
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
19578
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
19579
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
19580
0
}
19581
19582
// [DEBUG] Display contents of ImGuiStorage
19583
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
19584
0
{
19585
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
19586
0
        return;
19587
0
    for (int n = 0; n < storage->Data.Size; n++)
19588
0
    {
19589
0
        const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
19590
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
19591
0
    }
19592
0
    TreePop();
19593
0
}
19594
19595
// [DEBUG] Display contents of ImGuiTabBar
19596
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
19597
0
{
19598
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
19599
0
    char buf[256];
19600
0
    char* p = buf;
19601
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
19602
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
19603
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
19604
0
    p += ImFormatString(p, buf_end - p, "  { ");
19605
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
19606
0
    {
19607
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19608
0
        p += ImFormatString(p, buf_end - p, "%s'%s'",
19609
0
            tab_n > 0 ? ", " : "", (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???");
19610
0
    }
19611
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
19612
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19613
0
    bool open = TreeNode(label, "%s", buf);
19614
0
    if (!is_active) { PopStyleColor(); }
19615
0
    if (is_active && IsItemHovered())
19616
0
    {
19617
0
        ImDrawList* draw_list = GetForegroundDrawList();
19618
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
19619
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19620
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19621
0
    }
19622
0
    if (open)
19623
0
    {
19624
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
19625
0
        {
19626
0
            const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19627
0
            PushID(tab);
19628
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
19629
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
19630
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
19631
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???", tab->Offset, tab->Width, tab->ContentWidth);
19632
0
            PopID();
19633
0
        }
19634
0
        TreePop();
19635
0
    }
19636
0
}
19637
19638
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
19639
0
{
19640
0
    SetNextItemOpen(true, ImGuiCond_Once);
19641
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
19642
0
    {
19643
0
        ImGuiWindowFlags flags = viewport->Flags;
19644
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
19645
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
19646
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
19647
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
19648
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
19649
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
19650
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
19651
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
19652
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
19653
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
19654
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
19655
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
19656
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
19657
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
19658
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
19659
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
19660
0
            (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "",
19661
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
19662
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
19663
0
        for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
19664
0
            for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
19665
0
                DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
19666
0
        TreePop();
19667
0
    }
19668
0
}
19669
19670
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
19671
0
{
19672
0
    if (window == NULL)
19673
0
    {
19674
0
        BulletText("%s: NULL", label);
19675
0
        return;
19676
0
    }
19677
19678
0
    ImGuiContext& g = *GImGui;
19679
0
    const bool is_active = window->WasActive;
19680
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19681
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19682
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
19683
0
    if (!is_active) { PopStyleColor(); }
19684
0
    if (IsItemHovered() && is_active)
19685
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19686
0
    if (!open)
19687
0
        return;
19688
19689
0
    if (window->MemoryCompacted)
19690
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
19691
19692
0
    ImGuiWindowFlags flags = window->Flags;
19693
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
19694
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
19695
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
19696
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
19697
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
19698
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
19699
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
19700
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
19701
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
19702
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
19703
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
19704
0
    {
19705
0
        ImRect r = window->NavRectRel[layer];
19706
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
19707
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
19708
0
        else
19709
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
19710
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
19711
0
    }
19712
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
19713
19714
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
19715
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
19716
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
19717
0
    if (window->DockNode || window->DockNodeAsHost)
19718
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
19719
19720
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
19721
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
19722
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
19723
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
19724
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
19725
0
    {
19726
0
        for (int n = 0; n < window->ColumnsStorage.Size; n++)
19727
0
            DebugNodeColumns(&window->ColumnsStorage[n]);
19728
0
        TreePop();
19729
0
    }
19730
0
    DebugNodeStorage(&window->StateStorage, "Storage");
19731
0
    TreePop();
19732
0
}
19733
19734
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
19735
0
{
19736
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
19737
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
19738
0
}
19739
19740
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
19741
0
{
19742
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
19743
0
        return;
19744
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
19745
0
    {
19746
0
        PushID((*windows)[i]);
19747
0
        DebugNodeWindow((*windows)[i], "Window");
19748
0
        PopID();
19749
0
    }
19750
0
    TreePop();
19751
0
}
19752
19753
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
19754
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
19755
0
{
19756
0
    for (int i = 0; i < windows_size; i++)
19757
0
    {
19758
0
        ImGuiWindow* window = windows[i];
19759
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
19760
0
            continue;
19761
0
        char buf[20];
19762
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
19763
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
19764
0
        DebugNodeWindow(window, buf);
19765
0
        Indent();
19766
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
19767
0
        Unindent();
19768
0
    }
19769
0
}
19770
19771
//-----------------------------------------------------------------------------
19772
// [SECTION] DEBUG LOG WINDOW
19773
//-----------------------------------------------------------------------------
19774
19775
void ImGui::DebugLog(const char* fmt, ...)
19776
0
{
19777
0
    va_list args;
19778
0
    va_start(args, fmt);
19779
0
    DebugLogV(fmt, args);
19780
0
    va_end(args);
19781
0
}
19782
19783
void ImGui::DebugLogV(const char* fmt, va_list args)
19784
0
{
19785
0
    ImGuiContext& g = *GImGui;
19786
0
    const int old_size = g.DebugLogBuf.size();
19787
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
19788
0
    g.DebugLogBuf.appendfv(fmt, args);
19789
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
19790
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
19791
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
19792
0
}
19793
19794
void ImGui::ShowDebugLogWindow(bool* p_open)
19795
0
{
19796
0
    ImGuiContext& g = *GImGui;
19797
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
19798
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
19799
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
19800
0
    {
19801
0
        End();
19802
0
        return;
19803
0
    }
19804
19805
0
    AlignTextToFramePadding();
19806
0
    Text("Log events:");
19807
0
    SameLine(); CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
19808
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
19809
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
19810
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
19811
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
19812
0
    SameLine(); CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper);
19813
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
19814
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
19815
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
19816
19817
0
    if (SmallButton("Clear"))
19818
0
    {
19819
0
        g.DebugLogBuf.clear();
19820
0
        g.DebugLogIndex.clear();
19821
0
    }
19822
0
    SameLine();
19823
0
    if (SmallButton("Copy"))
19824
0
        SetClipboardText(g.DebugLogBuf.c_str());
19825
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
19826
19827
0
    ImGuiListClipper clipper;
19828
0
    clipper.Begin(g.DebugLogIndex.size());
19829
0
    while (clipper.Step())
19830
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
19831
0
        {
19832
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
19833
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
19834
0
            TextUnformatted(line_begin, line_end);
19835
0
            ImRect text_rect = g.LastItemData.Rect;
19836
0
            if (IsItemHovered())
19837
0
                for (const char* p = line_begin; p < line_end - 10; p++)
19838
0
                {
19839
0
                    ImGuiID id = 0;
19840
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
19841
0
                        continue;
19842
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
19843
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
19844
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
19845
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
19846
0
                        DebugLocateItemOnHover(id);
19847
0
                    p += 10;
19848
0
                }
19849
0
        }
19850
0
    if (GetScrollY() >= GetScrollMaxY())
19851
0
        SetScrollHereY(1.0f);
19852
0
    EndChild();
19853
19854
0
    End();
19855
0
}
19856
19857
//-----------------------------------------------------------------------------
19858
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
19859
//-----------------------------------------------------------------------------
19860
19861
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
19862
19863
void ImGui::DebugLocateItem(ImGuiID target_id)
19864
0
{
19865
0
    ImGuiContext& g = *GImGui;
19866
0
    g.DebugLocateId = target_id;
19867
0
    g.DebugLocateFrames = 2;
19868
0
}
19869
19870
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
19871
0
{
19872
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
19873
0
        return;
19874
0
    ImGuiContext& g = *GImGui;
19875
0
    DebugLocateItem(target_id);
19876
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
19877
0
}
19878
19879
void ImGui::DebugLocateItemResolveWithLastItem()
19880
0
{
19881
0
    ImGuiContext& g = *GImGui;
19882
0
    ImGuiLastItemData item_data = g.LastItemData;
19883
0
    g.DebugLocateId = 0;
19884
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
19885
0
    ImRect r = item_data.Rect;
19886
0
    r.Expand(3.0f);
19887
0
    ImVec2 p1 = g.IO.MousePos;
19888
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
19889
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
19890
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
19891
0
}
19892
19893
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
19894
void ImGui::UpdateDebugToolItemPicker()
19895
90.2k
{
19896
90.2k
    ImGuiContext& g = *GImGui;
19897
90.2k
    g.DebugItemPickerBreakId = 0;
19898
90.2k
    if (!g.DebugItemPickerActive)
19899
90.2k
        return;
19900
19901
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
19902
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
19903
0
    if (IsKeyPressed(ImGuiKey_Escape))
19904
0
        g.DebugItemPickerActive = false;
19905
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
19906
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
19907
0
    {
19908
0
        g.DebugItemPickerBreakId = hovered_id;
19909
0
        g.DebugItemPickerActive = false;
19910
0
    }
19911
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
19912
0
        if (change_mapping && IsMouseClicked(mouse_button))
19913
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
19914
0
    SetNextWindowBgAlpha(0.70f);
19915
0
    BeginTooltip();
19916
0
    Text("HoveredId: 0x%08X", hovered_id);
19917
0
    Text("Press ESC to abort picking.");
19918
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
19919
0
    if (change_mapping)
19920
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
19921
0
    else
19922
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
19923
0
    EndTooltip();
19924
0
}
19925
19926
// [DEBUG] Stack Tool: update queries. Called by NewFrame()
19927
void ImGui::UpdateDebugToolStackQueries()
19928
90.2k
{
19929
90.2k
    ImGuiContext& g = *GImGui;
19930
90.2k
    ImGuiStackTool* tool = &g.DebugStackTool;
19931
19932
    // Clear hook when stack tool is not visible
19933
90.2k
    g.DebugHookIdInfo = 0;
19934
90.2k
    if (g.FrameCount != tool->LastActiveFrame + 1)
19935
90.2k
        return;
19936
19937
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
19938
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
19939
6
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
19940
6
    if (tool->QueryId != query_id)
19941
0
    {
19942
0
        tool->QueryId = query_id;
19943
0
        tool->StackLevel = -1;
19944
0
        tool->Results.resize(0);
19945
0
    }
19946
6
    if (query_id == 0)
19947
6
        return;
19948
19949
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
19950
0
    int stack_level = tool->StackLevel;
19951
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
19952
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
19953
0
            tool->StackLevel++;
19954
19955
    // Update hook
19956
0
    stack_level = tool->StackLevel;
19957
0
    if (stack_level == -1)
19958
0
        g.DebugHookIdInfo = query_id;
19959
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
19960
0
    {
19961
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
19962
0
        tool->Results[stack_level].QueryFrameCount++;
19963
0
    }
19964
0
}
19965
19966
// [DEBUG] Stack tool: hooks called by GetID() family functions
19967
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
19968
0
{
19969
0
    ImGuiContext& g = *GImGui;
19970
0
    ImGuiWindow* window = g.CurrentWindow;
19971
0
    ImGuiStackTool* tool = &g.DebugStackTool;
19972
19973
    // Step 0: stack query
19974
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
19975
0
    if (tool->StackLevel == -1)
19976
0
    {
19977
0
        tool->StackLevel++;
19978
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
19979
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
19980
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
19981
0
        return;
19982
0
    }
19983
19984
    // Step 1+: query for individual level
19985
0
    IM_ASSERT(tool->StackLevel >= 0);
19986
0
    if (tool->StackLevel != window->IDStack.Size)
19987
0
        return;
19988
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
19989
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
19990
19991
0
    switch (data_type)
19992
0
    {
19993
0
    case ImGuiDataType_S32:
19994
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
19995
0
        break;
19996
0
    case ImGuiDataType_String:
19997
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
19998
0
        break;
19999
0
    case ImGuiDataType_Pointer:
20000
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20001
0
        break;
20002
0
    case ImGuiDataType_ID:
20003
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20004
0
            return;
20005
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20006
0
        break;
20007
0
    default:
20008
0
        IM_ASSERT(0);
20009
0
    }
20010
0
    info->QuerySuccess = true;
20011
0
    info->DataType = data_type;
20012
0
}
20013
20014
static int StackToolFormatLevelInfo(ImGuiStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20015
0
{
20016
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20017
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20018
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20019
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20020
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20021
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20022
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20023
0
        return (*buf = 0);
20024
#ifdef IMGUI_ENABLE_TEST_ENGINE
20025
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20026
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20027
#endif
20028
0
    return ImFormatString(buf, buf_size, "???");
20029
0
}
20030
20031
// Stack Tool: Display UI
20032
void ImGui::ShowStackToolWindow(bool* p_open)
20033
0
{
20034
0
    ImGuiContext& g = *GImGui;
20035
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20036
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20037
0
    if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20038
0
    {
20039
0
        End();
20040
0
        return;
20041
0
    }
20042
20043
    // Display hovered/active status
20044
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20045
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20046
0
    const ImGuiID active_id = g.ActiveId;
20047
#ifdef IMGUI_ENABLE_TEST_ENGINE
20048
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20049
#else
20050
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20051
0
#endif
20052
0
    SameLine();
20053
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
20054
20055
    // CTRL+C to copy path
20056
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
20057
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
20058
0
    SameLine();
20059
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
20060
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
20061
0
    {
20062
0
        tool->CopyToClipboardLastTime = (float)g.Time;
20063
0
        char* p = g.TempBuffer.Data;
20064
0
        char* p_end = p + g.TempBuffer.Size;
20065
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
20066
0
        {
20067
0
            *p++ = '/';
20068
0
            char level_desc[256];
20069
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
20070
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
20071
0
            {
20072
0
                if (level_desc[n] == '/')
20073
0
                    *p++ = '\\';
20074
0
                *p++ = level_desc[n];
20075
0
            }
20076
0
        }
20077
0
        *p = '\0';
20078
0
        SetClipboardText(g.TempBuffer.Data);
20079
0
    }
20080
20081
    // Display decorated stack
20082
0
    tool->LastActiveFrame = g.FrameCount;
20083
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
20084
0
    {
20085
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
20086
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
20087
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
20088
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
20089
0
        TableHeadersRow();
20090
0
        for (int n = 0; n < tool->Results.Size; n++)
20091
0
        {
20092
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
20093
0
            TableNextColumn();
20094
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
20095
0
            TableNextColumn();
20096
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
20097
0
            TextUnformatted(g.TempBuffer.Data);
20098
0
            TableNextColumn();
20099
0
            Text("0x%08X", info->ID);
20100
0
            if (n == tool->Results.Size - 1)
20101
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
20102
0
        }
20103
0
        EndTable();
20104
0
    }
20105
0
    End();
20106
0
}
20107
20108
#else
20109
20110
void ImGui::ShowMetricsWindow(bool*) {}
20111
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
20112
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
20113
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
20114
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
20115
void ImGui::DebugNodeFont(ImFont*) {}
20116
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
20117
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
20118
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
20119
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
20120
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
20121
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
20122
20123
void ImGui::DebugLog(const char*, ...) {}
20124
void ImGui::DebugLogV(const char*, va_list) {}
20125
void ImGui::ShowDebugLogWindow(bool*) {}
20126
void ImGui::ShowStackToolWindow(bool*) {}
20127
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
20128
void ImGui::UpdateDebugToolItemPicker() {}
20129
void ImGui::UpdateDebugToolStackQueries() {}
20130
20131
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
20132
20133
//-----------------------------------------------------------------------------
20134
20135
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
20136
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
20137
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
20138
#include "imgui_user.inl"
20139
#endif
20140
20141
//-----------------------------------------------------------------------------
20142
20143
#endif // #ifndef IMGUI_DISABLE